首页 > 解决方案 > 我需要将对象向量或大括号括起来的列表传递给构造函数的选项

问题描述

我的构造函数最初采用 astd::vector<>但我不知道如何获取一个花括号列表来初始化它。我在更改为std:initializer_list<>. 我找到了两种方法:1)将 initializer_list 作为参数传递给数组构造函数(在下面的代码中注释掉)和 2)使用std::copy算法(如下面的代码所示)。

现在,我需要用 a 创建这个对象,std::vector<>但不知道如何将它转换为 initializer_list。我可以制作第二个采用向量的构造函数,但作为练习,我希望尽可能使用一个构造函数。

有任何想法吗?

class One: public Base {
public:
  One( Two* ptwo_in, std::initializer_list<Three> ilthree ) :
    ptwo( ptwo_in )//,
    //athree_( ilthree )
  {
    athree_.reserve( ilthree .size() );
    std::copy( ilthree .begin(), ilthree .end(), athree_.begin() );
  }

  Two*               ptwo_;
  std::vector<Three> athree_;
};

  // Works fine:

  new One( &two, { Three( args ),
                   Three( args ),
                   Three( args ), } )



  // Doesn't work:

  std::vector<Three>* pathreeSomething
  athreeOther.push_back( new One( ptwoLocal, *pathreeSomething ) );

标签: c++initializer-liststdinitializerlist

解决方案


在第三行代码中,它可以将 initializer_list 替换为向量,true。但我不想将整个向量作为 arg 传递。

无论如何,您都将构建一个向量 ( One::athree_)。所以只需移动传递给构造函数的向量而不是复制它:

class One: public Base {
public:
    One(Two* ptwo_in, std::vector<Three> ilthree)
        : ptwo{ptwo_in}
        , athree_{std::move(ilthree)}
    { }

private:    
    Two* ptwo_;
    std::vector<Three> athree_;
};

这是 C++ 中的常见模式。通过非常量值传递并使用移动语义来避免复制:

One one{some_ptr, {Three{args}, Three{args}, Three{args}}};

或者:

std::vector<Three> vec{ ... };

// moves 'vec' to the ctor parameter, the ctor then moves it to its member
One one{some_ptr, std::move(vec)};

这样就没有不必要的副本了。


推荐阅读