C++ 状态模式实现:指向状态机的指针机制变得无效?
C++ State Pattern implementation: Mechanism of pointer to State Machine becoming invalid?
在尝试实现 "Head First Design Patterns" 书中的一个简单状态模式示例时,我遇到了一种让我觉得有点奇怪的情况。请注意,这个问题不是关于正确实施模式,而是关于理解导致观察到的行为的潜在机制。
机器 "Gumball_machine" 应该有几种可能的状态(No_quarter_state
、Has_quarter_state
、Sold_out_state
等),通过虚函数将行为委托给这些状态在运行时调用。这些状态是从抽象基 class State
公开继承的。 Gumball_machine
有一个 std::unique_ptr<State>
,State
class 本身是指向 Gumball_machine
的原始指针(因为没有假定所有权)。
当满足某些条件时会发生状态转换,它们通过分配新的具体状态 class 并将所有权转移到 Gumball_machine
.
来实现
(我将 post 一些代码示例放在这个 post 的末尾,因为我想先 "get to the point"。)
有一种情况,在同一个函数中切换状态后调用另一个函数:
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 将显示无效读取(错误消息将在下面显示)。
而这个我不是很明白。 ptr
和 machine_
应该引用同一个 Gumball_machine
实例,在程序结束之前不应该被销毁。 Has_quarter_state
(或者更确切地说父 class "State")只有一个没有所有权的原始指针。
现在想起来,大概是因为unique_ptr
-reset会导致Has_quarter_state
实例占用的内存被释放。这可能意味着任何后续操作,即对 Gumball_machine::dispense()
的函数调用,都会导致未定义的行为。这个假设是否正确?
如果内存地址 (&memory_ == &ptr
) 没有改变,为什么调用 ptr->dispense()
或 machine_->dispense()
会有所不同?
我觉得内存管理有一些复杂的地方我还是不明白。希望你能帮我解决问题。
下面我将 post 重现此代码("incorrect" 版本)和 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(); }
State.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
State.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_Whosebug/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_Whosebug/main)
==12085== by 0x402FF7: main (in /home/mbw/Documents/Programmieren/CPP/Design_Patterns/Head_First_Design_Patterns/Chapter10_State_pattern/Example1_Revised/example_for_Whosebug/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_Whosebug/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_Whosebug/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_Whosebug/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_Whosebug/main)
==12085== by 0x402FF7: main (in /home/mbw/Documents/Programmieren/CPP/Design_Patterns/Head_First_Design_Patterns/Chapter10_State_pattern/Example1_Revised/example_for_Whosebug/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)
提前感谢您的帮助!
问题是,当您用新的 std::unique_ptr
替换 _machine->state
时,您调用 turn_crank
的 Has_quarter_state
实例被破坏了:
machine_->state_ = std::make_unique<Sold_state>(machine_);
此处您要用包含另一个对象的新 unique_ptr
替换 machine_->state
。这意味着 ~unique_ptr<State>()
在为新的 Sold_state
构造新的 unique_ptr
之前被调用。但是唯一指针的当前拥有对象是 Has_quarter_state
实例,它在执行方法中被 this
隐式引用。
那你怎么办?
你做 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
,然后您尝试访问一个字段,该字段是已释放对象的一部分。
在尝试实现 "Head First Design Patterns" 书中的一个简单状态模式示例时,我遇到了一种让我觉得有点奇怪的情况。请注意,这个问题不是关于正确实施模式,而是关于理解导致观察到的行为的潜在机制。
机器 "Gumball_machine" 应该有几种可能的状态(No_quarter_state
、Has_quarter_state
、Sold_out_state
等),通过虚函数将行为委托给这些状态在运行时调用。这些状态是从抽象基 class State
公开继承的。 Gumball_machine
有一个 std::unique_ptr<State>
,State
class 本身是指向 Gumball_machine
的原始指针(因为没有假定所有权)。
当满足某些条件时会发生状态转换,它们通过分配新的具体状态 class 并将所有权转移到 Gumball_machine
.
(我将 post 一些代码示例放在这个 post 的末尾,因为我想先 "get to the point"。)
有一种情况,在同一个函数中切换状态后调用另一个函数:
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 将显示无效读取(错误消息将在下面显示)。
而这个我不是很明白。 ptr
和 machine_
应该引用同一个 Gumball_machine
实例,在程序结束之前不应该被销毁。 Has_quarter_state
(或者更确切地说父 class "State")只有一个没有所有权的原始指针。
现在想起来,大概是因为unique_ptr
-reset会导致Has_quarter_state
实例占用的内存被释放。这可能意味着任何后续操作,即对 Gumball_machine::dispense()
的函数调用,都会导致未定义的行为。这个假设是否正确?
如果内存地址 (&memory_ == &ptr
) 没有改变,为什么调用 ptr->dispense()
或 machine_->dispense()
会有所不同?
我觉得内存管理有一些复杂的地方我还是不明白。希望你能帮我解决问题。
下面我将 post 重现此代码("incorrect" 版本)和 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(); }
State.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
State.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_Whosebug/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_Whosebug/main)
==12085== by 0x402FF7: main (in /home/mbw/Documents/Programmieren/CPP/Design_Patterns/Head_First_Design_Patterns/Chapter10_State_pattern/Example1_Revised/example_for_Whosebug/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_Whosebug/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_Whosebug/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_Whosebug/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_Whosebug/main)
==12085== by 0x402FF7: main (in /home/mbw/Documents/Programmieren/CPP/Design_Patterns/Head_First_Design_Patterns/Chapter10_State_pattern/Example1_Revised/example_for_Whosebug/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)
提前感谢您的帮助!
问题是,当您用新的 std::unique_ptr
替换 _machine->state
时,您调用 turn_crank
的 Has_quarter_state
实例被破坏了:
machine_->state_ = std::make_unique<Sold_state>(machine_);
此处您要用包含另一个对象的新 unique_ptr
替换 machine_->state
。这意味着 ~unique_ptr<State>()
在为新的 Sold_state
构造新的 unique_ptr
之前被调用。但是唯一指针的当前拥有对象是 Has_quarter_state
实例,它在执行方法中被 this
隐式引用。
那你怎么办?
你做 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
,然后您尝试访问一个字段,该字段是已释放对象的一部分。