【发布时间】:2023-01-24 02:26:09
【问题描述】:
对于一项任务,我计划在 C++ 中实现一个状态机。 我试图保留一个提供以下内容的上下文对象:
- 用于跟踪当前状态的 state_ 对象
- 一个 TransitionTo() 方法来促进转换到新状态。
当我编写示例实现并对其进行测试时,我遇到了 double free 错误。
我需要社区的帮助来指导我了解可能出现的问题。 非常感谢。
#include <iostream> #include <string> class State; /* Context class and method implementation */ class Context { State* state_; public: explicit Context(State* state); void TransitionTo(State* newState); }; Context::Context (State* state): state_ (nullptr) { this->TransitionTo(state); } void Context::TransitionTo(State* newState) { std::cout <<"Requesting state transition to " << newState->stateName<<"\n"; std::string previous_state_name = "None"; if (this->state_ != nullptr) { previous_state_name = this->state_->stateName; delete this->state_; } this->state_ = newState; std::cout << "State changed from "<< previous_state_name << " to "<< this->state_->stateName << "\n"; this->state_->set_context(this); } /* State class and method implementation */ class State { protected: Context* context_; public: std::string stateName; void set_context(Context* newContext); virtual ~State(); }; State::~State() { std::cout << stateName <<" state deleted \n"; delete context_ ; } void State::set_context(Context *newContext) { this->context_ = newContext; } /* Declaring different states which are derived from State */ class HappyState : public State { public: HappyState(); }; HappyState::HappyState() { stateName = "Happy"; } class NeutralState : public State { public: NeutralState(); }; NeutralState::NeutralState() { stateName = "Neutral"; } class SadState : public State { public: SadState(); }; SadState::SadState() { stateName = "Sad"; } /* Test the implementation */ int main() { Context* ctx = new Context(( new NeutralState())); ctx->TransitionTo(new HappyState()); ctx->TransitionTo(new SadState()); return 0; }当我运行这段代码时,我得到以下输出: Output snapshot
【问题讨论】:
-
在你走得太远之前必须阅读:The rule of three/five/zero
-
int main() { State s; }即使是那个简单的程序也有问题。
标签: c++ memory segmentation-fault