简体   繁体   English

在类定义中使用删除的副本构造函数和初始化程序列表重载调用成员构造函数

[英]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
};

How to initialize Foo with two ints if the copy constructor is deleted? 如果复制构造函数被删除,如何用两个整数初始化Foo?

In order for that initialization to work, the type in question has to be MoveConstructible * . 为了使该初始化起作用,所讨论的类型必须为MoveConstructible * In your particular case, providing a move constructor would satisfy this requirement: 在您的特定情况下,提供一个move构造函数将满足此要求:

Foo(Foo&&) = default;

If this is not an option, you could initialize the member in a default constructor, and use it as a delegating constructor in other constructors. 如果这不是一个选项,则可以在默认构造函数中初始化该成员,并将其用作其他构造函数中的委派构造函数。

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

* This does not mean a copy will be made. *这并不意味着将进行复制。 T t = T() is an easy candidate for copy elision. T t = T()是复制省略的简单候选。 However, a viable constructor must be accessible. 但是,必须有可行的构造函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM