【问题标题】:What is happening in this std::vector constructor?这个 std::vector 构造函数中发生了什么?
【发布时间】:2017-09-09 21:07:55
【问题描述】:

我看到一个函数引用了一个 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;
}

谢谢。

【问题讨论】:

    标签: c++ c++11 vector constructor


    【解决方案1】:

    对于由这种结构创建的对象,您需要提供接受std::initializer_liststd::vector 的构造函数具有one (8)

    vector( std::initializer_list<T> init, 
            const Allocator& alloc = Allocator() );
    

    您也可以在该页面上看到一个示例:

    // c++11 initializer list syntax:
    std::vector<std::string> words1 {"the", "frogurt", "is", "also", "cursed"}; 
    

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

    Someobject {
       Someobject( int ){}
    };
    
    Someobject obj1(1); // usual way
    Someobject obj2{1}; // same thing since C++11
    

    但是你需要小心,如果对象之前提到过 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
    

    注意2:对于您的问题,文档中描述了列表的创建方式:

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

    一个花括号初始化列表用于列表初始化,包括函数调用列表初始化和赋值表达式

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

    【讨论】:

    • 初始化列表是如何从大括号列表中创建的?它是初始化列表中的转换构造函数吗?
    【解决方案2】:

    这称为std::initializer_list。从 C++11 开始就有了。

    这里是reference manual,了解它的工作原理。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-08
      相关资源
      最近更新 更多