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
等(,行为在运行时通过虚函数调用委托给它们。这些状态公开继承自抽象基类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将显示无效的读取(错误消息将显示在下面(。
这个我真的不明白。 ptr
和 machine_
应引用同一个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 3.6.0 通过clang++ -std=c++14 -stdlib=libc++
编译
现在对于实际代码(大大减少为一个最小示例(:
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 dispensedn";
}
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 gumballn";
}
void Sold_state::dispense()
{
std::cout << "A gumball comes rolling out the slotn";
// machine_->state_.reset(new No_quarter_state{machine_});
machine_->state_ = std::make_unique<Has_quarter_state>(machine_);
}
编辑:主要.cpp
int
main ()
{
Gumball_machine machine;
machine.turn_crank();
return 0;
}
最后是瓦尔格林德输出:
==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)
提前感谢您的帮助!
新std::unique_ptr
替换_machine->state
时,您调用turn_crank
Has_quarter_state
实例被销毁:
machine_->state_ = std::make_unique<Sold_state>(machine_);
在这里,您将machine_->state
替换为包含另一个对象的新unique_ptr
。这意味着在为新Sold_state
构建新unique_ptr
之前调用~unique_ptr<State>()
。但是唯一指针的当前拥有的对象是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
,然后你尝试访问一个字段,它是释放对象的一部分。
- 1d 智能指针不适用于语法 (*)++
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 为什么使用 "this" 指针调用派生成员函数?
- 函数向量_指针有不同的原型,我可以构建一个吗
- 使用指针从C++中的数组中获取最大值
- 助记符和指向成员语法的指针
- 嵌入方指针压缩已禁用
- 数组的指针从不分段故障
- C++ 指针的内存地址和指向数组的内存地址如何相同?
- 何时在引用或唯一指针上使用移动语义
- QMetaObject invokeMethod的基于函数指针的语法
- 如何从 std::atomic 中提取指针 T<T>?
- 使用共享指针时,从共享指针本身释放内存的机制是什么
- 将派生的对象地址分配给基础指针和调用击路仪的机制
- 可视C++指针机制 - 错误 2440
- 无法理解指针机制
- C++ 状态模式实现:指向状态机的指针机制变得无效
- 用宏遮蔽void*指针的机制
- 指针解引用:编译器的实际机制
- 使C函数指针与C++中基于C样式堆栈的调用机制一起工作