C++11 将成员唯一\u ptr初始化为空
在我的程序中,我有一组自定义类位置的对象。表态如下:C++11 将成员唯一\u ptr初始化为空,c++11,unique-ptr,C++11,Unique Ptr,在我的程序中,我有一组自定义类位置的对象。表态如下: class Position { public: Position(int x, int y); ~Position(); Actor *getActor() { return actor.get(); }; void setActor(Actor *actor) { actor = std::move(actor); }; Actor *clearActor()
class Position {
public:
Position(int x, int y);
~Position();
Actor *getActor() { return actor.get(); };
void setActor(Actor *actor) { actor = std::move(actor); };
Actor *clearActor() { return actor.release(); };
int getX() { return x; };
int getY() { return y; };
private:
int x, y;
std::unique_ptr<Actor> actor;
};
Position::Position(int x, int y)
{
this->x = x;
this->y = y;
actor.reset(nullptr);
}
但是,我知道这并没有正确地将存储的指针设置为nullptr,因为当我尝试在Position::getActor()内部调用actor.get()时,我会遇到如下错误:
class Position {
public:
Position(int x, int y);
~Position();
Actor *getActor() { return actor.get(); };
void setActor(Actor *actor) { actor = std::move(actor); };
Actor *clearActor() { return actor.release(); };
int getX() { return x; };
int getY() { return y; };
private:
int x, y;
std::unique_ptr<Actor> actor;
};
Position::Position(int x, int y)
{
this->x = x;
this->y = y;
actor.reset(nullptr);
}
第一次机会异常在0x01096486 in\uuuuuu.exe:0xc000005:访问冲突读取位置0x00000008。
是否有方法将成员唯一\u ptr初始化为nullptr?我知道我可以通过向Actor类添加一个变量来解决这个问题,该变量定义Actor是否处于活动状态,将unique_ptr设置为新的非活动Actor,并忽略所有非活动Actor,但如果可能的话,我宁愿避免这样做
谢谢
编辑:我添加了我调用getActor的代码:
bool Grid::addActor(Actor *actor, int x, int y)
{
Position *destination = at(x, y);
if (!destination->getActor()) {
destination->setActor(actor);
actor->setPosition(x, y);
actor->setGrid(this);
return true;
}
else {
inactive_actors.emplace_back(actor);
return false;
}
}
您不需要将std::unique指针初始化为null。只需将其保留为构造函数中的默认空值,并且仅将其重置为指向非空指针。您的错误如下:
void setActor(Actor *actor) { actor = std::move(actor); };
您正在将std::move
的结果分配给参数actor
。您可能是想使用参数actor
创建成员变量actor
:
void setActor(Actor *actor) { this->actor.reset(actor); };
作为补充说明,您只需将构造函数更改为:
Position::Position(int x, int y)
: x(x), y(y)
{
}
这将使用参数初始化成员
x
和y
,并默认将std::unique_ptr actor
初始化为null。是否取消引用getActor()
?是否使用位置指针调用它?对我有一个Position*pos,我正在检查pos->getActor()的值。现在是2015年,请使用。@broaderjayne如果getActor()
返回nullptr
,这是未定义的行为。@broaderjayne你正在取消引用getActor
返回的nullptr
吗?我将setActor更改为this->actor.reset(actor)
但仍遇到异常。另外,我是否也需要更改标头中的构造函数声明以匹配该格式?我从未使用过初始化列表;我才用C++编程了几个月,太棒了!我正要提到它。@Brotherjayne构造函数初始化列表是构造函数定义的一部分,就像主体一样,因此无需将它们放在构造函数声明中。我将构造函数更改为初始值设定项列表,但在尝试调用getActor()时仍会出现异常“牧师,你当然可以用它。你只是不允许取消引用它。例如,如果(!destination->getActor())
,那么每当getActor
返回一个时,您就使用null ptr
来检查目标位置是否存在一个actor。