gpt4 book ai didi

C++ 成员函数即使删除了调用它的对象也能够访问数据

转载 作者:太空宇宙 更新时间:2023-11-04 13:12:27 25 4
gpt4 key购买 nike

这是我遇到的一个场景:-

#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 对象。该对象通过 Agent 中的 update() 方法访问。这将调用 OnState 的执行方法。现在这个 execute 方法间接删除了调用它的 OnState 对象。然而在那之后,控制被传递回 OnState 对象中的 execute() 方法。更重要的是它能够打印 "id"的值。由于 delete currentState ,不应该删除指向的内存。

或者在某些情况下,系统可能会崩溃,并且在某些情况下,操作系统不会立即填满内存内容。

我认为函数定义并没有存储在特定于实例的内存中,但这并不能解释如何仍然可以访问“id”值。

代码的输出是:-

agent updating. will execute current State 
OnState executing
removing OnState id :- 0
removing State

删除 OnState 后执行?编号:- 0

问候。

最佳答案

只能删除指针,不能删除引用。检查这个link .这可能对您有所帮助。

关于C++ 成员函数即使删除了调用它的对象也能够访问数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39262928/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com