為什么這個代碼片段會輸出很多“這里”?
throw std::invalid_argument( "fool" );我認為程式應該在 after被呼叫時終止。
#include <memory>
#include <iostream>
void* operator new(std::size_t size)
{
std::cout << "here" << std::endl;
throw std::invalid_argument( "fool" ); //commit out this, there would be many many ouputs
return std::malloc(size);
}
void operator delete(void* ptr)
{
return free(ptr);
}
int main()
{
//std::unique_ptr<int> point2int(new int(999));
int* rawpoint2int = new int(666);
}
uj5u.com熱心網友回復:
的檔案包含std::invalid_argument線索:
std::invalid_argument因為不允許復制引發例外,所以此訊息通常在內部存盤為單獨分配的參考計數字串。這也是為什么沒有建構式采用的原因std::string&&:無論如何它都必須復制內容。
您可以看到字串引數是按設計復制的。new這意味著如果您以這種方式拋出此例外,則幾乎可以保證重新輸入。
您還應該知道malloccan return nullptrwhich 將違反operator new哪個應該回傳有效指標或 throw 的設計。
在這種情況下拋出的正常例外是std::bad_alloc. 我無法想象你為什么要扔std::invalid_argument。我想也許你在某處的建構式中遇到了這個問題,并決定測驗分配本身。
從技術上講,您可以通過將默認構造的字串作為引數傳遞來解決問題:
// ... but, why would you do this?!! :(
throw std::invalid_argument(std::string()); // will not allocate
哇,好惡心。我建議你找到一個更合適的例外來拋出(如果你真的需要一個),或者創建你自己的非分配例外。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/440820.html
上一篇:帶有可變引數模板的標準哈希
下一篇:全域多載前綴運算子 /--
