【问题标题】:using std::initializer_list as a member variable [duplicate]使用 std::initializer_list 作为成员变量 [重复]
【发布时间】:2017-12-31 23:05:10
【问题描述】:

我有一个 A 类,它接受 initializer_list 并将其存储为成员变量。

class A
{
public:
    A(std::initializer_list<std::string> il) :
        m_il(il)
    {}

    std::initializer_list<std::string> m_il;
};

另一个类B 具有A 作为默认使用initializer_list 初始化的成员变量

class B
{
public:
    B()
    {
        std::cout << *m_a.m_il.begin() << std::endl;
    }

    A m_a { "hello", "bye" };
};

现在,当我在 main 中运行此代码时,它什么也不打印。

int main()
{
    B b;
}

为什么上面的代码没有打印hello?我对std::initializer_list 的用法不正确吗?

【问题讨论】:

  • 不要使用initializer_list作为数据成员。
  • 初始化非静态类成员甚至被提到 here 作为专门延长底层临时的生命周期

标签: c++ c++11


【解决方案1】:

复制std::initializer_list 不会复制其底层对象。它不打算用作容器。您应该做的是将其存储在其他东西中,例如 std::vector:

class A
{
public:
    A(std::initializer_list<std::string> il) :
        m_il(il)
    {}

    std::vector<std::string> m_il;
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-31
    相关资源
    最近更新 更多