gpt4 book ai didi

C++ 状态模式实现 : Mechanism of pointer to State Machine becoming invalid?

转载 作者:行者123 更新时间:2023-11-30 05:33:47 25 4
gpt4 key购买 nike

在尝试实现“Head First Design Patterns”一书中的一个简单状态模式示例时,我遇到了一种让我觉得很奇怪的情况。请注意,这个问题不是关于正确实现模式,而是关于理解导致观察到的行为的潜在机制。

机器“Gumball_machine”应该有几种可能的状态(No_quarter_stateHas_quarter_stateSold_out_state 等),在运行时通过虚函数调用将行为委托(delegate)给这些状态。这些状态是从抽象基类公开继承的 State . Gumball_machine有一个 std::unique_ptr<State> , State类本身是指向 Gumball_machine 的原始指针(因为没有假定所有权)。

当满足某些条件时会发生状态转换,它们通过分配新的具体状态类并将所有权转移到 Gumball_machine 来发生。 .

(我将在本文末尾发布一些代码示例,因为我想先“切入正题”。)

有一种情况,在同一个函数中切换状态后调用另一个函数:

void Has_quarter_state::turn_crank()
{
std::cout << "You turned...\n";
machine_->state_ = std::make_unique<Sold_state>(machine_);
machine_->dispense(); // Invalid read!

// This works however (don't forget to comment out the above reallocation):
// Gumball_machine* ptr{machine_};
// machine_->state_ = std::make_unique<Sold_state>(machine_);
// ptr->dispense();
}

machine_作为指向 Gumball_machine 的指针, 和 state_作为std::unique_ptr<State>到具体状态,Has_quarter_state .

如果我声明临时指针 ptr并调用 Gumball_machine::dispense() , 没有问题。但是,如果我只是调用 machine_->dispense() , valgrind 将显示无效读取(错误消息将在下面显示)。

这个我不是很明白。 ptrmachine_应该引用相同的 Gumball_machine实例,在程序结束之前不应被销毁。 Has_quarter_state (或者更确切地说,父类“State”)只有一个没有所有权的原始指针。

现在想起来,大概是因为unique_ptr - 重置会导致内存被 Has_quarter_state 占用要释放的实例。这可能意味着任何后续操作,即对 Gumball_machine::dispense() 的函数调用, 会导致未定义的行为。这个假设是否正确?如果内存地址 ( &memory_ == &ptr ) 没有改变,为什么我调用 ptr->dispense() 会有所不同?或 machine_->dispense()

我觉得内存管理有些复杂,我还是不明白。希望您能帮我解决问题。

下面我将发布重现这个(“不正确”版本)的代码和 valgrind 给我的错误消息(使用 --leak-check=full--leak-kinds=all )。

代码通过 clang++ -std=c++14 -stdlib=libc++ 编译使用 clang 3.6.0

现在是实际代码(大大简化为更小的示例):

Gumball_machine.hpp:

#ifndef CLASS_GUMBALL_MACHINE_HPP_
#define CLASS_GUMBALL_MACHINE_HPP_

#include <memory>

class State;

class Gumball_machine
{
friend class Has_quarter_state;
friend class Sold_state;
public:
Gumball_machine();
~Gumball_machine();

void turn_crank();

private:
void dispense();

private:
std::unique_ptr<State> state_;

};
#endif

Gumball_machine.cpp:

#include "Gumball_machine.hpp"

#include "Has_quarter_state.hpp"

Gumball_machine::Gumball_machine() : state_{std::make_unique<Has_quarter_state>(this)} {}
Gumball_machine::~Gumball_machine() {}

void Gumball_machine::turn_crank() { state_->turn_crank(); }
void Gumball_machine::dispense() { state_->dispense(); }

状态.hpp:

#ifndef CLASS_STATE_HPP_
#define CLASS_STATE_HPP_

class Gumball_machine;

class State
{
public:
explicit State(Gumball_machine* m);
virtual ~State();

virtual void turn_crank() = 0;
virtual void dispense() = 0;

protected:
Gumball_machine* machine_ = nullptr;
};
#endif

状态.cpp:

#include "State.hpp"
State::State(Gumball_machine* m) : machine_{m} {}
State::~State() {}

Has_quarter_state.hpp:

#ifndef ClASS_HAS_QUARTER_STATE_HPP_
#define ClASS_HAS_QUARTER_STATE_HPP_

#include "State.hpp"

class Gumball_machine;

class Has_quarter_state : public State
{
public:
explicit Has_quarter_state(Gumball_machine*);
~Has_quarter_state() override;

void turn_crank() override;
void dispense() override;
};
#endif

Has_quarter_state.cpp:

#include "Has_quarter_state.hpp"

#include <iostream>

#include "Gumball_machine.hpp"
#include "Sold_state.hpp"

Has_quarter_state::Has_quarter_state(Gumball_machine* m) : State{m} {}
Has_quarter_state::~Has_quarter_state() {}

void Has_quarter_state::turn_crank()
{
std::cout << "You turned...\n";
machine_->state_ = std::make_unique<Sold_state>(machine_);
machine_->dispense(); // Invalid read!

// This works however (don't forget to comment out the above reallocation):
// Gumball_machine* ptr{machine_};
// machine_->state_ = std::make_unique<Sold_state>(machine_);
// ptr->dispense();
}
void Has_quarter_state::dispense()
{
std::cout << "No gumball dispensed\n";
}

Sold_state.hpp:

#ifndef ClASS_SOLD_STATE_HPP_
#define ClASS_SOLD_STATE_HPP_

#include "State.hpp"

class Gumball_machine;

class Sold_state : public State
{
public:
explicit Sold_state(Gumball_machine*);
~Sold_state() override;

void turn_crank() override;
void dispense() override;

};
#endif

Sold_state.cpp:

#include "Sold_state.hpp"

#include <iostream>

#include "Gumball_machine.hpp"
#include "Has_quarter_state.hpp"

Sold_state::Sold_state(Gumball_machine* m) : State{m} {}
Sold_state::~Sold_state() {}

void Sold_state::turn_crank()
{
std::cout << "Turning twice doesn't give you another gumball\n";
}

void Sold_state::dispense()
{
std::cout << "A gumball comes rolling out the slot\n";
// machine_->state_.reset(new No_quarter_state{machine_});
machine_->state_ = std::make_unique<Has_quarter_state>(machine_);
}

编辑: main.cpp

     int 
main ()
{
Gumball_machine machine;
machine.turn_crank();
return 0;
}

最后是 valgrind 输出:

==12085== Memcheck, a memory error detector
==12085== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al.
==12085== Using Valgrind-3.10.1 and LibVEX; rerun with -h for copyright info
==12085== Command: ./main
==12085==
==12085== Invalid read of size 8
==12085== at 0x401C61: Has_quarter_state::turn_crank() (in /home/mbw/Documents/Programmieren/CPP/Design_Patterns/Head_First_Design_Patterns/Chapter10_State_pattern/Example1_Revised/example_for_stackoverflow/main)
==12085== by 0x401730: Gumball_machine::turn_crank() (in /home/mbw/Documents/Programmieren/CPP/Design_Patterns/Head_First_Design_Patterns/Chapter10_State_pattern/Example1_Revised/example_for_stackoverflow/main)
==12085== by 0x402FF7: main (in /home/mbw/Documents/Programmieren/CPP/Design_Patterns/Head_First_Design_Patterns/Chapter10_State_pattern/Example1_Revised/example_for_stackoverflow/main)
==12085== Address 0x5e47048 is 8 bytes inside a block of size 16 free'd
==12085== at 0x4C2CE10: free (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==12085== by 0x4017B4: operator delete(void*, unsigned long) (in /home/mbw/Documents/Programmieren/CPP/Design_Patterns/Head_First_Design_Patterns/Chapter10_State_pattern/Example1_Revised/example_for_stackoverflow/main)
==12085== by 0x401858: Has_quarter_state::~Has_quarter_state() (in /home/mbw/Documents/Programmieren/CPP/Design_Patterns/Head_First_Design_Patterns/Chapter10_State_pattern/Example1_Revised/example_for_stackoverflow/main)
==12085== by 0x401B27: Has_quarter_state::turn_crank() (in /home/mbw/Documents/Programmieren/CPP/Design_Patterns/Head_First_Design_Patterns/Chapter10_State_pattern/Example1_Revised/example_for_stackoverflow/main)
==12085== by 0x401730: Gumball_machine::turn_crank() (in /home/mbw/Documents/Programmieren/CPP/Design_Patterns/Head_First_Design_Patterns/Chapter10_State_pattern/Example1_Revised/example_for_stackoverflow/main)
==12085== by 0x402FF7: main (in /home/mbw/Documents/Programmieren/CPP/Design_Patterns/Head_First_Design_Patterns/Chapter10_State_pattern/Example1_Revised/example_for_stackoverflow/main)
==12085==
==12085==
==12085== HEAP SUMMARY:
==12085== in use at exit: 0 bytes in 0 blocks
==12085== total heap usage: 3 allocs, 3 frees, 48 bytes allocated
==12085==
==12085== All heap blocks were freed -- no leaks are possible
==12085==
==12085== For counts of detected and suppressed errors, rerun with: -v
==12085== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)

预先感谢您的帮助!

最佳答案

问题是 Has_quarter_state您正在调用的实例 turn_crank当您替换 _machine->state 时被销毁有了新的 std::unique_ptr :

 machine_->state_ = std::make_unique<Sold_state>(machine_);

在这里你要替换machine_->state有了新的 unique_ptr其中包含另一个对象。这意味着 ~unique_ptr<State>()在构建新的 unique_ptr 之前被调用对于新的 Sold_state .但是唯一指针的当前拥有对象是Has_quarter_statethis 隐式引用的实例在执行方法中。

那你怎么办?

你做machine_->dispense()这是this->machine_->dispense()但是machine_是刚刚被销毁的对象的实例变量(您在其上调用了当前正在执行的方法),因此它的值不再有效。

正在分配 machine_临时工作,因为您在销毁对象之前复制了对象成员字段的内容。因此您仍然可以正确访问机器。

不使用 std::unique_ptr并且通过强制每个状态管理自己的释放,你会发现有些地方是错误的,因为(几乎)等效的代码(这将是一个非常糟糕的设计)如下:

void Has_quarter_state::turn_crank() {
this->machine_->state_ = new Sold_state();
delete this;
this->machine_->dispense();
}

现在你首先看到你delete this ,然后您尝试访问一个字段,该字段是已释放对象的一部分。

关于C++ 状态模式实现 : Mechanism of pointer to State Machine becoming invalid?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34572493/

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