【问题标题】:C++ State Pattern implementation: Mechanism of pointer to State Machine becoming invalid?C++ 状态模式实现:指向状态机的指针机制变得无效?
【发布时间】:2016-04-06 23:08:42
【问题描述】:

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

机器“Gumball_machine”应该有几种可能的状态(No_quarter_stateHas_quarter_stateSold_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_ 是指向具体状态 Has_quarter_statestd::unique_ptr&lt;State&gt;

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

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

现在想来,大概是因为unique_ptr-reset会导致Has_quarter_state实例占用的内存被释放。这可能意味着任何后续操作,即对Gumball_machine::dispense() 的函数调用,都会导致未定义的行为。这个假设正确吗? 如果内存地址(&amp;memory_ == &amp;ptr)没有改变,为什么我调用ptr-&gt;dispense()machine_-&gt;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(); }

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_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)

提前感谢您的帮助!

【问题讨论】:

  • @dfri 是的,我只是注意到我忘了添加一个主函数。我编辑了我的帖子以弥补这一点。

标签: c++ pointers c++14 dangling-pointer


【解决方案1】:

问题在于,当您将_machine-&gt;state 替换为新的std::unique_ptr 时,您正在调用turn_crankHas_quarter_state 实例被破坏:

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

在这里,您将 machine_-&gt;state 替换为包含另一个对象的新 unique_ptr。这意味着在为新的Sold_state 构造新的unique_ptr 之前调用~unique_ptr&lt;State&gt;()。但是唯一指针当前拥有的对象是Has_quarter_state实例,在执行方法中被this隐式引用。

那你怎么办?

您使用machine_-&gt;dispense(),即this-&gt;machine_-&gt;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,然后您尝试访问作为已释放对象一部分的字段。

【讨论】:

  • 这个答案用我能理解的术语完美地解释了这个问题。感谢您的快速回复!
猜你喜欢
  • 2016-04-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多