无法在 class 中初始化 unique_ptr 的向量
Can't initialize a vector of unique_ptr in class
目前,我有两个 classes,Ai
和 Action
。
我的 class Ai
得到了一个名为 _root
的成员 Action
。
class Ai
{
public:
Ai();
~Ai();
private:
Action _root;
};
当我想用我的构造函数 Ai
.
初始化 class Action
时出现问题
Ai::Ai() : _root(Action(0, AI, 0, 0))
{
}
我的 classAction
和我的构造函数:
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
的向量。
我的调试器给我这个错误:
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
中的成员变量。
class Action
不是用户定义的移动构造函数。它确实有一个用户定义的析构函数,可以防止自动生成移动构造函数。 Action
至少有一个成员 (_child
) 无法复制。因此,Action
也没有复制构造函数。
在 C++11 中,只有当 Action
具有可访问的复制或移动构造函数时,才能执行 _root(Action(0, AI, 0, 0))
。它两者都没有。要解决这个问题,您要么直接构造 _root
(参见 1201ProgramAlarm 的回答),要么让编译器通过添加
为您生成移动构造函数
Action(Action&&) = default;
See this example 对于 C++11
在 C++17 中,规则发生了变化,由于 mandatory copy/move elision,_root(Action(0, AI, 0, 0))
等同于 _root(0, AI, 0, 0)
。代码应该在没有可用的复制和移动构造函数的情况下编译(除非有其他编译失败的原因)。
See this example 用于 C++17
目前,我有两个 classes,Ai
和 Action
。
我的 class Ai
得到了一个名为 _root
的成员 Action
。
class Ai
{
public:
Ai();
~Ai();
private:
Action _root;
};
当我想用我的构造函数 Ai
.
Action
时出现问题
Ai::Ai() : _root(Action(0, AI, 0, 0))
{
}
我的 classAction
和我的构造函数:
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
的向量。
我的调试器给我这个错误:
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
中的成员变量。
class Action
不是用户定义的移动构造函数。它确实有一个用户定义的析构函数,可以防止自动生成移动构造函数。 Action
至少有一个成员 (_child
) 无法复制。因此,Action
也没有复制构造函数。
在 C++11 中,只有当 Action
具有可访问的复制或移动构造函数时,才能执行 _root(Action(0, AI, 0, 0))
。它两者都没有。要解决这个问题,您要么直接构造 _root
(参见 1201ProgramAlarm 的回答),要么让编译器通过添加
Action(Action&&) = default;
See this example 对于 C++11
在 C++17 中,规则发生了变化,由于 mandatory copy/move elision,_root(Action(0, AI, 0, 0))
等同于 _root(0, AI, 0, 0)
。代码应该在没有可用的复制和移动构造函数的情况下编译(除非有其他编译失败的原因)。
See this example 用于 C++17