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;
};
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" };
};
Now when I run this code in main, it prints nothing.
int main()
{
    B b;
}
Why did the code above not print hello? Is my usage of std::initializer_list incorrect?
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;
};
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With