繁体   English   中英

如何编写正确的std :: initializer_list构造函数

[英]How to write proper std::initializer_list constructor

考虑以下代码:

#include <iostream>
#include <vector>

struct C {
    std::vector<int> a;
    std::string b;
    bool c;
};

void printC(const C &c) {
    // ...
}

int main() {
    printC({
        { 1, 2, 3 },
        "ehlo",
        false
    });
}

这是有效的,因为编译器可以为我生成适当的构造函数。 但是,如果我将struct C更改为:

struct C {
    std::vector<int> a;
    std::string b;
    bool c;

    C() {
        c = false;
    }
};

printC调用停止工作,因为编译器停止生成适当的构造函数。 我试过用std :: initializer_list写自己的构造函数但是失败了。

所以问题是 - 如何编写构造函数,使上面的代码再次编译和工作?

我试过用std :: initializer_list写自己的构造函数但是失败了。

你不需要一个。 你只需要一个带矢量,字符串和布尔值的c'tor:

C(std::vector<int> a, std::string b, bool c) 
  : a(std::move(a))
  , b(std::move(b))
  , c(c) {
}

您的代码现在应该再次构建良好。 虽然现在它会产生两个移动操作,而原始聚合版本可以直接初始化对象的元素。 这是值得考虑的事情。

值得注意的是,在C ++ 14及更高版本中,您只需使用默认成员初始值设定项:

struct C {
    std::vector<int> a;
    std::string b;
    bool c = false;
};

此外,聚合初始化不会生成构造函数。 它完全绕过它们。

您可以像这样传递std::initializer_list<int>的实例:

#include <initializer_list>

struct C {
    /* Data members... */

    C(std::initializer_list<int> vecData, std::string str, bool flag) :
        a{vecData}, b{std::move(str)}, c{flag} {}
};

暂无
暂无

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

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