Consider the following code:
#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?
}
我原以为
D d5{{}};
会使用空列表调用D
的initializer_list
构造函数,且由于列表为空,C
的构造函数不会被调用。然而,它无法编译:
这个错误背后的原理是什么?错误:使用已删除的函数
'C::C()'
--D d5{{}};
更新
在Scott Meyer的"Effective Modern C++"第55页上的一个问题让我认为,在花括号初始化中使用空括号将使用空列表调用initializer_list
构造函数。这是错误的。有关详细信息,请参见作者的博客文章。