1

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

机器“Gumball_machine”应该有几种可能的状态(No_quarter_stateHas_quarter_stateSold_out_state等),在运行时通过虚拟函数调用将行为委托给这些状态。这些状态是从一个抽象基类公开继承的StateGumball_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_machinestate_std::unique_ptr<State>Has_quarter_state

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

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

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

已售状态.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

已售状态.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)

预先感谢您的帮助!

4

1 回答 1

1

问题是当您替换为 new时Has_quarter_state,您正在调用的实例turn_crank被破坏:_machine->statestd::unique_ptr

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

在这里,您将替换为包含另一个对象machine_->state的新对象。unique_ptr这意味着在为~unique_ptr<State>()new 构造 new 之前调用。但是唯一指针当前拥有的对象是在执行方法中隐式引用的实例。unique_ptrSold_stateHas_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();
}

现在您首先看到了 you delete this,然后您尝试访问作为已释放对象一部分的字段。

于 2016-01-03T01:46:47.920 回答