C++11统一初始化和函数重载

4

简单程序:

void f(const std::string& s);
void f(const char* p);
f({});

为什么clang会调用f((const char*)nullptr)呢?我本来期望编译器会对这个模棱两可的调用发出警告。
1个回答

3

这个问题在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 ]


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接