簡體   English   中英

C ++我不明白我的異常what()行為

[英]C++ I don't understand my exceptions what() behavior

我正在用what()方法編寫一個異常類。

const char* what() const throw() {
    return "test";
}

工作正常,但是

const char* what() const throw() {
    return (std::string("test")).c_str();
}

似乎返回一個隨機的結果。 為什么?

std::string("test")創建一個臨時字符串對象。 c_str返回指向該臨時對象的某個內部存儲的指針。 函數退出后,這是一個懸空指針 - 它指向無效的內存。

沒有辦法繞過這個。 您必須通過在函數外部聲明(並初始化,因為函數是const )來使您的字符串對象更長壽 - 或者您需要在函數內手動分配堆存儲,在那里復制字符串,並返回指針到那個存儲。 但是,這很復雜,容易出錯,並且違反了函數的約定,因為錯誤類的用戶不期望釋放內存。

事實上,這是一個錯誤類的簡單實現(玩具,因為我不知道你的用例),考慮到這一點:

struct my_logic_error : std::logic_error {
    // `std::logic_error` already overrides `what`, we only need to initialise it!
    my_logic_error(int errcode) :
        std::logic_error{std::string{"Logic error occurred with error code "} +
                std::to_string(errcode)} {}
};

假設您從沒有這種奢侈的異常類派生,您的代碼變得最簡單:

struct my_error : std::exception {
    my_error(int errcode) :
        message{std::string{"Logic error occurred with error code "} +
                std::to_string(errcode)} {}

    char const* what() const noexcept {
        return message.c_str();
    }

private:
    std::string message;
};

將字符串值存儲在異常類的成員中,並在此成員上返回c_str()。

做一個strdup可以工作,但調用者必須釋放內存,這不是一種安全的做法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM