我需要将对象向量或大括号括起来的列表传递给构造函数的选项

I need the option of passing in a vector of objects, or brace-enclosed list, to a constructor

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

现在,我需要用 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 ) );

On that third line of code it works with replacing initializer_list with vector, true. But I don't want to pass around a whole vector as an 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++ 中的常见模式。通过 non-const 值传递并使用移动语义来避免复制:

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)};

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