[英]explicit constructor in std::runtime_error
根據cplusplus.com,這是std :: runtime_error類的實現:
class runtime_error : public exception {
public:
explicit runtime_error (const string& what_arg);
};
由於構造函數是顯式的,我希望它僅接受std :: string對象。
throw std::runtime_error("error message");
但是,此代碼會編譯(GCC)。 編譯器是否應該抱怨隱式const char *到const字符串轉換?
這不是明確的意思。 也許用一個例子最簡單地說明一下:
struct Foo
{
explicit Foo(const std::string& s) {}
};
void bar(const Foo&) {}
int main()
{
Foo f("hello"); // OK: explicit construction from std::string
Foo f2 = std::string("hello"); // ERROR
std::string s;
bar(s); // ERROR
}
在這里, explicit
轉換構造函數意味着您不能從std::string
隱式構造Foo
。 但是您仍然可以從const char*
構造std::string
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.