问题描述
我有一个 A
类,它使用 initializer_list
并将其存储为成员变量。
I have a class A
that takes an initializer_list
and stores it as a member variable.
class A
{
public:
A(std::initializer_list<std::string> il) :
m_il(il)
{}
std::initializer_list<std::string> m_il;
};
另一类 B
具有 A
作为成员变量,默认使用 initializer_list
Another class B
has A
as a member variable that is default initialized using the initializer_list
class B
{
public:
B()
{
std::cout << *m_a.m_il.begin() << std::endl;
}
A m_a { "hello", "bye" };
};
现在,当我在main中运行此代码时,它什么也不会打印。
Now when I run this code in main, it prints nothing.
int main()
{
B b;
}
上面的代码为什么不打印 hello
?我对 std :: initializer_list
的用法不正确吗?
Why did the code above not print hello
? Is my usage of std::initializer_list
incorrect?
推荐答案
std :: initializer_list
不会复制其基础对象。它并不是要用作容器。相反,您应该做的是将其存储在其他内容中,例如 std :: vector
:
Copying a std::initializer_list
does not copy its underlying objects. It's not meant to be used as a container. What you should be doing instead is storing it in something else, like a std::vector
:
class A
{
public:
A(std::initializer_list<std::string> il) :
m_il(il)
{}
std::vector<std::string> m_il;
};
这篇关于使用std :: initializer_list作为成员变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!