2016-09-22 53 views
2

我們希望自己定義std::runtime_error:runtime_error(const string& arg)。我們在其他構造方面實現這樣的構造,即std::runtime_error:runtime_error(const char*),如:gcc 4.9.1不符合標準? (std :: runtime_error)

namespace std { 
    runtime_error::runtime_error(const string& arg) 
    : runtime_error(arg.c_str()) { 
    ... 
    } 
} 

用gcc-4.9.1,這是不可能的,因爲構造std::runtime_error::runtime_error(const string& arg)不存在。在GCC/4.9.1 /包括/ C++/4.9.1/stdexcept,我們看到以下內容:

... 
class runtime_error : public exception 
{ 
    string _M_msg; 
    public: 
    /** Takes a character string describing the error. */ 
    explicit 
    runtime_error(const string& __arg); 
    virtual ~runtime_error() _GLIBCXX_USE_NOEXCEPT; 
    /** Returns a C-style character string describing the general cause of 
    * the current error (the same string passed to the ctor). */ 
    virtual const char* 
    what() const _GLIBCXX_USE_NOEXCEPT; 
}; 
... 

標準明確表示,應該有一個明確的runtime_error(const char*)構造函數。

19.2.6類runtime_error [runtime.error]

namespace std { 
class runtime_error : public exception { 
public: 
explicit runtime_error(const string& what_arg); 
explicit runtime_error(const char* what_arg); 
}; 
+5

「*我們根據其他構造函數實現了這樣的構造函數*」爲什麼你想要?接受'std :: string'的長度內置了一個長度,而另一個必須使用'strlen'來計算長度。這只是毫無意義的浪費時間。另外,您不允許在標準庫中重寫類。 –

+0

你正在使用'-std = C++ 11'嗎? –

+0

@FredLarson應該是默認值。 –

回答

1

也許這不回答你原來的問題,但如果目的真的是攔截runtime_error實例,你可以這樣做(asuming GCC使用):

namespace std { 
    runtime_error::runtime_error(const string& arg) 
    #if (__GNUC__ > 4) 
    : runtime_error(arg.c_str()) 
    #else 
    : _M_msg(arg) 
    #endif 
    { 
    // intercept here! 
    } 
} 

希望調用的runtime_error(const char*)不會在未來的runtime_error(const string&)而言,這將打破所有的希望和願望實現。 =)