ser*_*gej 3 c++ initializer-list c++11 list-initialization c++14
考虑以下代码:
#include <initializer_list>
class C {
public:
C() = delete;
C(int) {}
};
class D {
public:
D(std::initializer_list<C> il) {}
};
int main()
{
std::initializer_list<C> il{}; // fine: empty list, no need to construct C
D d2(il); // fine: calls initializer_list ctor with empty list
D d3{il}; // ditto
D d4({}); // still fine
D d5{{}}; // error: use of deleted function 'C::C()'
// WHY is the constructor of 'C' required here?
}
Run Code Online (Sandbox Code Playgroud)
我想D d5{{}};会用一个空列表调用initializer_list构造函数D。并且,由于列表为空,C不会调用的构造函数。但是,它不会编译:
错误:使用已删除的函数
'C::C()'--D d5{{}};
这个错误背后的原因是什么?
Scott Meyer 的“Effective Modern C++”第 55 页上的一个问题让我认为在花括号初始化中使用空花括号会调用initializer_list带有空列表的构造函数。那是错的。有关详细信息,请参阅作者的这篇博文。