为什么 std::string{"const char ptr"} 有效?

Why std::string{"const char ptr"} works?

我可以看到 std::string 只有一个 CTOR 与 initializer_liststring (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,但它不是可行的候选者,当 stringconst 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"};
}

Live version