3

假设我有一些删除了复制构造函数的类:

struct NoCopy
{
    NoCopy(int) {}
    NoCopy(const NoCopy &) = delete;
};

我在另一个类中使用这个类:

struct Aggregate
{
    NoCopy nc;
};

但是当我尝试使用聚合初始化时

int main()
{
    Aggregate a{3};
}

编译器输出以下错误:

error: use of deleted function ‘NoCopy::NoCopy(const NoCopy&)’

为什么聚合初始化需要类成员的复制构造函数?聚合初始化是否使用复制构造函数初始化所有成员?

4

1 回答 1

7

The correct syntax for what you want is:

Aggregate a{{3}};

This provides an initializer for the NoCopy member. Without the extra {} the compiler needs to perform a conversion from int to NoCopy (which it happily does via the non-explicit constructor), and then use that to construct nc. This would normally occur as a move construction but by deleting the copy ctor you have effictively deleted the move constructor as well.

An easier way to think about it might be to imagine NoCopy had a value constructor taking two arguments instead of one:

struct NoCopy {
    NoCopy(int, int);
};

Now if you wrote

Aggregate a{1, 2};

that would indicate that 1 is used to initialize nc and 2 is used to initialize something else (compile-time error). You'd have to add the extra {} for this to make sense

Aggregate a{{1, 2}};

A third way involves looking at a function call:

struct NoCopy {
  NoCopy(int) {}
  NoCopy(const NoCopy &) = delete;
};

void fun(NoCopy) { }

int main() {
  fun(1); // wrong
  fun({1}); // right
}

In the // wrong version, a temporary NoCopy object is constructed at the callsite using the NoCopy(int) constructor. Then that temporary is passed by value into fun, but since NoCopy isn't copyable, it fails.

In the // right version you are providing the initializer list for the argument to be constructed with. No copies are made.

于 2015-12-19T08:20:27.057 回答