在基构造函数中初始化唯一指针的标准容器

Initialize standard container of unique pointers in base constructor

本文关键字:标准 指针 唯一 构造函数 初始化      更新时间:2023-10-16

如果在编译时容器及其内容是已知的,那么在基构造函数中初始化具有唯一指针的标准库容器的首选方法是什么?c++不允许初始化列表与唯一指针一起使用,因为它们强制执行复制操作,所以我目前使用了一个丑陋的lambda解决方案:

#include <memory>
#include <vector>
#include <string>
using namespace std; // Note: for readability only
// Some non-POD object
class Object {
public: 
    Object(const string& desc) : description(desc) { }
    string description;
    void func () { /* do stuff */ }
};
// This class stores a vector of unique pointers to objects
class BaseX {
public:
    const vector< unique_ptr<const Object> > objects;
    BaseX (vector< unique_ptr<Object> > vec) : 
        objects { make_move_iterator(vec.begin()), make_move_iterator(vec.end()) } { }
};
// This class is a special case of BaseX where the object definitions are constant, and known at compile time (static).
// Question is how to initialize them...
class DerivedX : public BaseX {
public:
    DerivedX () : BaseX(
        // Using a lambda function is a messy idea, but works
        []()->vector< unique_ptr<Object> > {
            unique_ptr<Object> objects[] = {
                make_unique<Object>("My object")
            };
            return { make_move_iterator(begin(objects)), make_move_iterator(end(objects)) };
        }()
    ) { }
};

这似乎是一个应该使用static的情况,但不确定它适合在哪里…

我可能会这样做:

class DerivedX : public BaseX {
public:
  DerivedX () : BaseX(make_vec()) { }
private:
  static auto make_vec()
  {
    std::vector<std::unique_ptr<const O>> v(2);
    v[0] = std::make_unique<O>("1");
    v[1] = std::make_unique<O>("2");
    return v;
  }
};

(使用auto返回类型,因为您似乎正在使用c++ 14,如果您有make_unique,如果您使用c++ 11,那么只需显式拼写返回类型。)

相关文章: