2017-10-11 100 views
4

經過12年的間歇後回到C++開發。我使用JetBrains的CLion軟件,這非常棒,因爲它提供了關於我的班級設計中可能出現的問題的大量輸入。我在課堂上的構造函數throw statement中得到的警告之一是:Thrown exception type is not nothrow copy constructible。以下是生成此警告的代碼示例:處理「拋出的異常類型不是無法複製可構造的」警告

#include <exception> 
#include <iostream> 

using std::invalid_argument; 
using std::string; 

class MyClass { 
    public: 
     explicit MyClass(string value) throw (invalid_argument); 
    private: 
     string value; 
}; 

MyClass::MyClass(string value) throw (invalid_argument) { 
    if (value.length() == 0) { 
     throw invalid_argument("YOLO!"); // Warning is here. 
    } 

    this->value = value; 
} 

這段代碼可以編譯,我可以對它進行單元測試。但我非常想擺脫這個警告(爲了理解我做錯了什麼,即使它編譯了)。

謝謝

+1

爲什麼使用throw規格?棄用。 https://stackoverflow.com/questions/13841559/deprecated-throw-list-in-c11 –

+1

痛苦'拋出'說明符帶來。太痛苦了。最好沒有,你是。 – user4581301

回答

1

Neil提供的評論是有效的。在C++ 11中,在函數簽名中使用throw已被棄用,以支持noexcept。在這種情況下,我的構造方法的簽名應該是:

explicit MyClass(string value) noexcept(false); 

但是,因爲noexcept(false)默認情況下適用於所有的功能,除非指定noexceptnoexcept(true),我可以簡單地使用:

explicit MyClass(string value); 

展望回到如何解決「拋出異常類型不是無法複製可構造」的警告,我發現this post很好地解釋了這個問題是什麼以及如何解決這個問題。

相關問題