简单程序:
void f(const std::string& s);
void f(const char* p);
f({});
为什么clang会调用
f((const char*)nullptr)
呢?我本来期望编译器会对这个模棱两可的调用发出警告。简单程序:
void f(const std::string& s);
void f(const char* p);
f({});
f((const char*)nullptr)
呢?我本来期望编译器会对这个模棱两可的调用发出警告。这个问题在C++11标准的草案中有所涉及,具体规定见 13.3.3.1.5
[over.ics.list]。该草案规定如下:
Otherwise, if the parameter type is not a class:
[...]
if the initializer list has no elements, the implicit conversion sequence is the identity conversion. [ Example:
void f(int); f( { } ); // OK: identity conversion
—end example ]
所以,一个身份转换比构造函数调用更好。
我们得到nullptr的原因是因为它正在对指针进行值初始化。根据第8.5.4
节 [dcl.init.list]:
List-initialization of an object or reference of type T is defined as follows:
[...]
Otherwise, if the initializer list has no elements, the object is value-initialized. [ Example:
int** pp {}; // initialized to null pointer
—end example ]