Search code examples
c++initializer-list

Can't I return a list initialization directly in C++?


struct vec2{float x,y;};

This will work:

vec2* window(float h, float w)
{
    vec2 ret[4] = {{w,h},{1-w,h},{1-w,1-h},{w,1-h}};
    return ret;
}

But this won't:

vec2* window(float h, float w)
{
    return {{w,h},{1-w,h},{1-w,1-h},{w,1-h}};
}

I guess the error comes from the fact that the latter doesn't specify the size of the array, but I don't know if I'm missing something...

I also tried:

return vec2[4]({{w,h},{1-w,h},{1-w,1-h},{w,1-h}});

Solution

  • You can't return an array by value, and you mustn't return a pointer to an automatic or temporary object, since it will be destroyed when the function returns, leaving the pointer invalid.

    Return std::array if the size is a known, small constant or std::vector otherwise.