Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to return a std::initializer_list from a function?

The following works:

struct A {
    int i;
    int v;
};

std::initializer_list<A> getList() {
    return {A{0,1}, A{2,3}};
}

int main() {
    auto list = getList();
}

I can verify that the contents of list is correct.

However, if I change the member v to a std::vector, it does not work:

struct A {
    int i;
    std::vector<int> v;
};

std::initializer_list<A> getList() {
    return {A{0,{1,2}}, A{3,{4,5}}};
}

in this case, the returned list contains junk values.

I know the standard says that the underlaying objects are not copied when a std::initializer_list is copied. Is this what happens here?

Why did it work in the first example? Was it luck? Is it something special with the case when the objects in the list contains a std::vector?

like image 221
user2479653 Avatar asked Dec 02 '25 07:12

user2479653


1 Answers

Returning initializer_list compiles, but it seldom does the right thing. The list is a temporary value and the initializer_list object points to it. It is a dangling pointer.

In your first example, an optimization is applied because the list is a constant expression. Instead of being written into temporary storage, it is a static global. However, this optimization is not specified in the standard. The return value working, is only a form of undefined behavior.

like image 193
Potatoswatter Avatar answered Dec 04 '25 21:12

Potatoswatter