我可以看到 std::string 只有一个 CTOR 为 initializer_list
: string (initializer_list<char> il);
所以初始化列表应该使用字符,对吧?为什么 std::string{"some_str"}
有效,它得到 const char*
,对吧?
最佳答案
n3337 13.3.1.7/1
When objects of non-aggregate class type T are list-initialized (8.5.4), overload resolution selects the constructor in two phases:
— Initially, the candidate functions are the initializer-list constructors (8.5.4) of the class T and the argument list consists of the initializer list as a single argument.
— If no viable initializer-list constructor is found, overload resolution is performed again, where the candidate functions are all the constructors of the class T and the argument list consists of the elements of the initializer list.
std::string
有很多 constructors .其中之一,接收 const char*
。
因此,首先编译器将在重载解析中采用 initializer_list
c-tor,但当 string
由 const char*< 构造时,它不是可行的候选者
,然后编译器会查看其他构造函数并选择最好的一个,即
basic_string( const CharT* s,
const Allocator& alloc = Allocator() );
你可以用简单的例子来检查它:
#include <initializer_list>
#include <iostream>
class String
{
public:
String(const std::initializer_list<char>&) { std::cout << "init-list c-tor called" << std::endl; }
String(const char*) { std::cout << "const char* c-tor called" << std::endl; }
};
int main()
{
String s{"hello"};
}
关于c++ - 为什么 std::string {"const char ptr"} 有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33298375/