使用删除的复制构造函数和初始化列表重载调用 class 定义中的成员构造函数

Calling a member constructor in class definition with a deleted copy constructor and initializer list overload

struct Foo
{
    Foo(const Foo&) = delete;
    Foo(int a, int b);
    Foo(std::initializer_list<int>);    
};

struct Bar
{
    Foo f = Foo(1, 2);
    // Foo f = {1, 2} - calls the initializer_list overload
};

如果删除了复制构造函数,如何用两个整数初始化 Foo?

为了使初始化工作,相关类型必须是 MoveConstructible*。在您的特定情况下,提供移动构造函数将满足此要求:

Foo(Foo&&) = default;

如果这不是一个选项,您可以在默认构造函数中初始化该成员,并将其用作其他构造函数中的委托构造函数。

struct Bar
{
    Bar() : f(1, 2) {}
    Bar(const FooBar&) : Bar() {}
    Bar(double x) : Bar() {}
    Foo f;
};

* 这并不意味着将进行复制。 T t = T() 很容易成为复制省略的候选者。但是,一个可行的构造函数必须是可访问的。