我刚开始学习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
被破坏后可以调用成员函数?