![](/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.