简体   繁体   中英

What is happening in this std::vector constructor?

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.

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

This is called std::initializer_list . It's there since C++11.

Here's the reference manual on how it works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM