Reputation: 14112
I saw a function which takes a reference to an std::vector, and the argument passed to it has confused me as to what's happening. It looked like this:
void aFunction(const std::vector<int>& arg) { }
int main()
{
aFunction({ 5, 6, 4 }); // Curly brace initialisation? Converting constructor?
std::vector<int> arr({ 5, 6, 4 }); // Also here, I can't understand which of the constructors it's calling
return 0;
}
Thanks.
Upvotes: 2
Views: 110
Reputation: 44268
For object to be created by such structure you need to provide constructor that accepts std::initializer_list and std::vector
has one (8):
vector( std::initializer_list<T> init,
const Allocator& alloc = Allocator() );
you can see an example on that page as well:
// c++11 initializer list syntax:
std::vector<std::string> words1 {"the", "frogurt", "is", "also", "cursed"};
Note: C++11 also allows objects to be initialized by curly brackets:
Someobject {
Someobject( int ){}
};
Someobject obj1(1); // usual way
Someobject obj2{1}; // same thing since C++11
but you need to be careful though, if object has ctor mentioned before it would be used instead:
std::vector<int> v1( 2 ); // creates vector with 2 ints value 0
std::vector<int> v2{ 2 }; // creates vector with 1 int value 2
Note2: for your question how list created it is described in documentation:
A std::initializer_list object is automatically constructed when:
a braced-init-list is used in list-initialization, including function-call list initialization and assignment expressions
a braced-init-list is bound to auto, including in a ranged for loop
Upvotes: 5
Reputation: 26326
This is called std::initializer_list
. It's there since C++11.
Here's the reference manual on how it works.
Upvotes: 1