![](/img/trans.png)
[英]C++ SFINAE : is_constructible for const char[] vs std::string
[英]C++: choosing a `const char *` vs `std::string` when using delegating constructor
考慮以下:
class Foo {
public:
Foo (const char *in) {
printf ("C string constructor called\n");
}
Foo (std::string const &in) : Foo(in.c_str()) {
printf ("C++ string constructor called\n");
}
};
Foo bar ("I never asked for this");
//C string constructor called
因此,常量string
被視為const char *
one。
但是,如果我們將std::string
構造函數std::string
“ primary”,會發生什么變化呢?
我們是否可以期望將創建一個std::string
對象並將其傳遞給相應的構造函數,而無需調用與C字符串相關的對象?
class Foo {
public:
Foo (std::string const &in) {
printf ("C++ string constructor called\n");
}
Foo (const char *in) : Foo(std::string (in)) {
printf ("C string constructor called\n");
}
};
Foo bar ("I never asked for this");
//C++ string constructor called
//C string constructor called
同樣,C字符串構造函數被稱為first 。
是在C ++標准中描述了此行為,還是與編譯器相關?
對於模板或重載函數,這將以相同的方式工作嗎?
我使用GCC 7.3.0(MSYS2 x64)進行了編譯。
C ++中沒有像主構造函數這樣的東西。
您觀察到的是,首先執行了委托給構造函數( 目標構造函數 )的主體。 然后是委托的構造函數的主體( delegating constructor )。
委托構造函數 :
在這種情況下,將通過重載決議選擇目標構造函數並首先執行它,然后控件返回到委派構造函數,並執行其主體。
重載解析和構造函數委派是兩個完全不同的事物,它們根本不會相互影響。
重載解析避免了可能的隱式轉換。
像"I never asked for this"
這樣的字符串文字是const char[]
,它會衰減為const char *
。 這與您的const char *
構造const char *
完全匹配,因此被調用。 用字符串文字作為輸入來調用std::string
構造函數將需要進行隱式轉換,因為編譯器將構造一個臨時的std::string
對象以綁定到std::string const &
reference。
您是否編寫了此代碼:
Foo bar (std::string("I never asked for this"));
或這個:
std::string str = "I never asked for this";
Foo bar (str);
然后將調用std::string const &
構造std::string const &
而不是const char *
構造函數,因為沒有從std::string
到const char *
隱式轉換。
在編譯器決定調用哪個構造函數之后,構造函數如何相互委托是一個實現細節 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.