这是我遇到的一个场景:
#include <iostream>
class Agent;
class State;
class OffState;
class OnState;
class State
{
public:
virtual void execute(Agent * agent) = 0;
virtual ~State() {std::cout << "removing State\n";}
};
class Agent{
State * currentState ;
public:
Agent();
void update(){
std::cout << "agent updating. will execute current State " << std::endl;
currentState->execute(this);
}
void changeState(State * newState){
delete currentState;
currentState = newState;
}
};
class OffState : public State
{
public:
~OffState() {std::cout << "deleting OffState Object" <<std::endl;}
void execute(Agent * agent){
std::cout << "Nothing happens in the off State " << std::endl;
}
};
class OnState : public State
{
static int count ;
int id;
public:
OnState(){
id = count;
count++;
}
~OnState() {std::cout << "removing OnState id :- " <id<<std::endl;}
void execute(Agent * agent){
std::cout << "OnState executing" << std::endl;
agent->changeState(new OffState());
std::cout << "executed after deleting OnState ? id:- " << id << std::endl;
}
};
int OnState::count = 0;
Agent::Agent():currentState(new OnState()){
}
main(){
Agent smith;
smith.update();
}
在这种情况下,代理的当前状态被初始化为OnState对象。可通过代理中的update()方法访问此对象。这将调用OnState的execute方法。现在,此execute方法间接删除调用它的OnState对象。之后,控制权将被传递回OnState对象中的execute()方法。更重要的是,它能够打印“ id”的值。不应由于删除currentState而删除指向的内存。
还是在某些情况下系统可能崩溃并且在某些情况下操作系统不会立即填充内存内容的情况。
我以为函数定义没有存储在特定于实例的内存中,但这并不能解释“ id”值如何仍然可访问。
代码的输出为:-
agent updating. will execute current State
OnState executing
removing OnState id :- 0
removing State
删除OnState后执行? id:-0
问候。
最佳答案
您只能删除指针,不能删除引用。
选中此link。这可能对您有帮助。
关于c++ - 即使删除了调用它的对象,C++成员函数也能够访问数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39262928/