Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weird syntax for push_back function in std::vector

I came across the following syntax for the push_back function. Vertex is just a structure that holds the three floats x, y and z. The second line looks just like would write it. But the first line looks weird to me. In the video where this was explained it was said that this is done with the member initializer list but it looks more like implicit conversion. I am just confused by the curly brackets there. Can anyone explain why this syntax works?

std::vector<Vertex> vertices;

vertices.push_back({ 1, 2, 3 });
vertices.push_back(Vertex(1, 2, 3));
like image 339
Nicky Avatar asked Mar 25 '20 10:03

Nicky


1 Answers

This is not member initializer list but copy list initialization (since C++11).

7) in a function call expression, with braced-init-list used as an argument and list-initialization initializes the function parameter

vertices.push_back() expects an Vertex as the argument, the braced-init-list { 1, 2, 3 } is used to construct a temporary Vertex which is passed to push_back later. As you said, you can think it as implicit conversion too, i.e. the conversion from the braced-init-list to Vertex.

like image 119
songyuanyao Avatar answered Oct 09 '22 23:10

songyuanyao