我想重新實作標準例外層次結構。
std::exception根據檔案,以下列方式定義:
class exception {
public:
exception () noexcept;
exception (const exception&) noexcept;
exception& operator= (const exception&) noexcept;
virtual ~exception();
virtual const char* what() const noexcept;
}
現在,例如,std::logic_error宣告如下:
class logic_error : public exception {
public:
explicit logic_error (const string& what_arg);
explicit logic_error (const char* what_arg);
};
我的問題是,這樣的實體化:如何在幕后std::logic_error("Error!")作業?
錯誤!” string 被傳遞給logic_error (const char* what_arg),并以某種方式將其值傳遞給實作中的what()多載,而不呼叫它。
這樣做的一種方法可能是復制字串并將其存盤在某處(作為私有成員,在基類中),然后將其放入what().
我只是想澄清這是否是我應該做的。我知道例外應該盡可能輕量級。我想避免存盤任何物件。
有沒有好的方法來實作這個?
uj5u.com熱心網友回復:
是的,他們很可能將字串存盤在私有成員中。
std::string雖然不是一個簡單的,因為復制那些可以拋出。可能相當于std::shared_ptr<std::string>.
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/406205.html
標籤:
