This question already has an answer here:
I just start learning c++11 for a short time and met a problem I don't understand. Here is the simplified example I met in a code base:
#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;
}
Based on my understanding, when Test
is destructed, mObject
is destructed first, then mDerived
is destructed, then Base
then Dumper
. When Dumpper
is destructed, mDumpFunc
is called, in which member function of mObject
is called. But why the member function can be called after mObject
is destructed?
Aucun commentaire:
Enregistrer un commentaire