【发布时间】:2015-02-28 03:39:05
【问题描述】:
在我的程序中,我有一堆自定义类位置的对象。 Position的声明如下:
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;
};
我还有一个名为 Actor 的类。不是每个位置都会有一个 Actor,因此大多数时候位置对象的 unique_ptr “actor”应该是空的(我使用 unique_ptrs 在运行时自动清理与位置关联的任何 Actor)。
Position构造函数如下:
Position::Position(int x, int y)
{
this->x = x;
this->y = y;
actor.reset(nullptr);
}
但是,我知道这没有正确地将存储的指针设置为 nullptr,因为当我尝试在 Position::getActor() 中调用 actor.get() 时,我收到如下错误:
____.exe 中 0x01096486 处的第一次机会异常:0xC0000005:访问冲突读取位置 0x00000008。
有没有办法将成员 unique_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;
}
}
【问题讨论】:
-
你要取消引用
getActor()吗? -
您的意思是使用位置指针调用它吗?是的。我有一个 Position *pos,我正在检查 pos->getActor() 的值。
-
@PreacherJayne 如果
getActor()返回nullptr,这是未定义的行为。 -
@PreacherJayne 您是否取消引用
getActor返回的nullptr?
标签: c++11 unique-ptr