c++ - 无法在类中初始化 unique_ptr 的 vector

标签 c++ class pointers vector initialization

目前,我有两个类(class),AiAction .

我的类(class) Ai获得成员(member)Action称为 _root .

class Ai
{
  public:
    Ai();
    ~Ai();
  private:
    Action _root;
};

当我想初始化我的类时出现问题Action和我的构造函数 Ai .

Ai::Ai() : _root(Action(0, AI, 0, 0)) 
{
}

我的类(class) Action与我的构造函数:

class Action
{
public:
  Action(int, Availability, int, int);
  ~Action();
  private:
    int _y;
    int _x;
    int _depth;
    Availability _type;
    vector<unique_ptr<Action>> _child;
};

Action::Action(int depth, Availability type, int y, int x)
{
  this->_y = y;
  this->_x = x;
  this->_depth = depth;
  this->_type = type;
}

问题恰恰发生在 vector<unique_ptr<Action>> _child; 上.

当我创建对象时 Ai ,我的构造函数创建了一个对象 Action使用默认值,但它不能初始化 unique_ptr 的 vector .

我的调试器给我这个错误:

error: call to implicitly-deleted copy constructor of
  'std::__1::unique_ptr<Action, std::__1::default_delete<Action> >'
        ::new((void*)__p) _Up(_VSTD::forward<_Args>(__args)...);

有什么想法吗?

最佳答案

您声明 Ai 构造函数的方式是创建一个临时 Action 对象,然后将其复制到 _root.

解决方法很简单:

Ai::Ai() : _root(0, AI, 0, 0)

将构造函数参数直接传递给 _root

无关,你不需要使用this->来访问Action::Action中的成员变量。

关于c++ - 无法在类中初始化 unique_ptr 的 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59119541/

相关文章:

c++ - 我应该为赋值运算符使用左值引用限定符吗?

c++ - 结构和函数(通过引用传递)

.net - 托管 C++ 中的 ServiceController? (。网)

c++ - std::atomic 错误:没有为后缀 ‘operator++(int)’ 声明 ‘++’ [-fpermissive]

java - lucee中如何导入java.security.KeyStore.PasswordProtection

c++ - 在类的成员函数定义中使用 (::)

c++ - 自定义类的正确构造函数

c - C中带指针的for循环

使用函数更改指针包含的地址

c++ - 使用 QGLWidget 作为 QGraphicsView 的视口(viewport)导致黑屏