Can std :: initalizer_list cause lifelong problems?

When using std::initializer_list, I had some difficulties. It did not take me much time to understand that I thought of it more as a container, when in fact it has reference semantics. So my question is: which of the following examples can cause problems, and if not, why do they work? I must add that I am using VS2013, and std::initializer_listimplemented using only the start and end pointer.

Example 1

const auto tmpList = {1, 2, 3};
const vector<int> test(tmpList);

This may work if literals 1, 2, and 3 are stored in a contiguous block of memory. But is it guaranteed?

Example 2

const string a("foo");
int someOtherVariable = 10;
const string b("bar");
const auto tmpList = {a, b};
const vector<string> test(tmpList);

, a b ( std::initializer_list ). , - , :

const vector<string> test({a, b});

?

3

const auto tmpList = {string("foo"), string("bar")};
const vector<string> test(tmpList);

.

, , std::initializer_list . , ( )? , - , , .

, . , VS2013 ++. , :

const auto tmpList = {join(myList1), join(myList2)};
const vector<string> test(tmpList);

join - , a std::string. 2 , . :

const auto str1 = join(myList1);
const auto str2 = join(myList2);
const auto tmpList = {str1, str2};
const vector<string> test(tmpList);

, , , , , .. , .

+3
2

. § 8.5.4/5

std::initializer_list<E> , N const E, N - . , std::initializer_list<E> .... [:

 struct X {
X(std::initializer_list<double> v);
};
X x{ 1,2,3 };

:

const double __a[3] = {double{1}, double{2}, double{3}};
X x(std::initializer_list<double>(__a, __a+3));

...- end example]

, §8.5.4/6

, (12.2), , initializer_list , .

. :

struct A {
    std::initializer_list<int> i4;
    A() : i4{ 1, 2, 3 } {} // creates an A with a dangling reference
};

, , , , , i4 .

+4

++ 11 8.5.4/6 , initializer_list.

, . - ,

std::initializer_list<int> bad;
{
    bad = {1,2,3};
}
std::vector<int> test(bad);  // Boom!

.

+4

All Articles