I was checking some code and I encountered the following scenario. It's working fine but it sounds like an undefined behaviour to me but I don't know what to search and how to prove it.
#include <memory>
#include <functional>
#include <string>
#include <iostream>
class Child
{
public:
Child()
{
std::cout << "Child created\n";
}
~Child()
{
std::cout << "Child is dead\n";
}
};
class Parent
{
std::unique_ptr<Child> m_child;
public:
using Callback = std::function<void()>;
Parent(const Callback& killMe)
{
std::cout << "Parent created\n";
killMe();
m_child = std::make_unique<Child>();
}
~Parent()
{
std::cout << "Parent is dead\n";
}
};
class GrandParent
{
std::unique_ptr<Parent> m_child;
public:
GrandParent()
{
m_child = std::make_unique<Parent>([this]() { KillChild(); });
}
void KillChild()
{
m_child.reset();
}
};
int main()
{
{
GrandParent gp;
}
return 0;
}
I expected that, Parent
get killed before creation of Child
but apparently it's not the case, I tried it on multiple compilers and always got the following output :
Parent created
Child created
Parent is dead
Child is dead