这个std :: vector构造函数发生了什么?

Zeb*_*ish 2 c++ constructor vector c++11

我看到一个函数引用了一个std :: vector,传递给它的参数让我对发生的事情感到困惑.它看起来像这样:

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;
}
Run Code Online (Sandbox Code Playgroud)

谢谢.

Sla*_*ica 5

对于要由此类结构创建的对象,您需要提供接受std :: initializer_list并且std::vector具有一个(8)的构造函数:

vector( std::initializer_list<T> init, 
        const Allocator& alloc = Allocator() );
Run Code Online (Sandbox Code Playgroud)

你也可以看到该页面上的一个例子:

// c++11 initializer list syntax:
std::vector<std::string> words1 {"the", "frogurt", "is", "also", "cursed"}; 
Run Code Online (Sandbox Code Playgroud)

注意:C++ 11还允许用大括号初始化对象:

Someobject {
   Someobject( int ){}
};

Someobject obj1(1); // usual way
Someobject obj2{1}; // same thing since C++11
Run Code Online (Sandbox Code Playgroud)

但是你需要小心,如果对象有ctor之前提到它将被使用:

std::vector<int> v1( 2 ); // creates vector with 2 ints value 0
std::vector<int> v2{ 2 }; // creates vector with 1 int value 2
Run Code Online (Sandbox Code Playgroud)

注意2:对于您的问题,列表创建方式如下所述:

在以下情况下自动构造std :: initializer_list对象:

在列表初始化中使用了braced-init-list,包括函数调用列表初始化和赋值表达式

braced-init-list绑定到auto,包括在ranged for循环中