Using std :: initializer_list as a member variable

I have a class A that takes an initializer_list and saves 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; }; 

Another class B has A as a member variable, which is initialized by default with initializer_list

 class B { public: B() { std::cout << *m_a.m_il.begin() << std::endl; } A m_a { "hello", "bye" }; }; 

Now when I run this code basically, it doesn't print anything.

 int main() { B b; } 

Why didn't the code above print hello ? Is using std::initializer_list wrong?

+7
c ++ c ++ 11
source share
1 answer

Copy std::initializer_list does not copy its underlying objects. It is not intended to be used as a container. Instead, you should store it in something else, like std::vector :

 class A { public: A(std::initializer_list<std::string> il) : m_il(il) {} std::vector<std::string> m_il; }; 
+6
source share

All Articles