c ++在析构函数中使用非拥有指针

时间:2016-07-28 17:47:53

标签: c++ c++11

我刚开始学习c ++ 11很短的时间,遇到了一个我不明白的问题。以下是我在代码库中遇到的简化示例:

#include <functional>
#include <iostream>
#include <memory>
#include <string>
#include <utility>

class Dumpper {
 public:
  Dumpper(std::function<void()> func) : mDumpFunc(std::move(func)) {}

  ~Dumpper() {
    mDumpFunc();
  }

 private:
  std::function<void()> mDumpFunc;
};

class Object {
 public:
  std::string getInfo() {
    return "Object's information";
  }
};

class Base {
 protected:
  void InitDumpper(std::function<void()> func) {
    mDumpper.reset(new Dumpper(func));
  }
 private:
  std::unique_ptr<Dumpper> mDumpper;
};

class Derived : public Base {
 public:
  Derived(Object* object) : Base(), mObject(object) {
    InitDumpper(std::bind(&Derived::DumpFunc, this));
  }
 private:
  void DumpFunc() {
    std::cout << "Call DumpFunc, object = " << mObject->getInfo() << std::endl;
  }

  Object* mObject;  // Not owned.
};

class Test {
 public:
  Test() {
    mObject.reset(new Object);
    mDerived.reset(new Derived(mObject.get()));
  }
 private:
  std::unique_ptr<Derived> mDerived;
  std::unique_ptr<Object> mObject;
};

int main(int argc, char *argv[])
{
  Test test;
  return 0;
}

根据我的理解,当Test被破坏时,mObject首先被破坏,然后mDerived被破坏,然后Base然后Dumper。当Dumpper被破坏时,将调用mDumpFunc,其中调用mObject的成员函数。但是为什么在mObject被破坏后可以调用成员函数?

0 个答案:

没有答案