I've tried the C++0x initializer-list implementation of my G++ version but it outputs only empty lines.
#include <initializer_list>
#include <iostream>
#include <string>
int main() {
std::initializer_list<std::string> a({"hello", "stackoverflow"});
for(auto it = a.begin(), ite = a.end(); it != ite; ++it)
std::cout << *it << std::endl;
}
I have no idea what I did wrong. Can anyone help me out please?
It looks like you're creating two initializer lists in the example above. Temporary
{"hello", "stackoverflow"}andstd::initializer_list<std::string> a.On gcc,
{}initializer lists are in fact temporary arrays whose lifetime ends after full statement (unless bound directly tostd::initializer_listlike in the commented line in the example below).The lifetime of internal array of the first list ends right after
a's constructor returns and thusa's array now points to invalid memory (gcc only copies the pointer). You can check, thatstd::stringdestructors get called before you enter the loop.And when you get to loop, you're reading invalid memory.
According to lastest standard draft (n3242), §18.9/1, initializer lists cannot be even copied like that (they provide no constructor with parameters).
With gcc 4.5.0, I get