Skip to content

Instantly share code, notes, and snippets.

@olibre
Forked from odeblic/smart_dtor.cpp
Last active October 7, 2018 21:10
Show Gist options
  • Save olibre/90dc7cb3d47b6d57defc99191dffc39c to your computer and use it in GitHub Desktop.
Save olibre/90dc7cb3d47b6d57defc99191dffc39c to your computer and use it in GitHub Desktop.
Smart destructor
/*
* Original work: https://gist.github.com/odeblic/fa54037bf4d764a5dc02735cb4bd79f3
* Inspired from: https://youtu.be/ZiNGWHg5Z-o
*
* Compile
*
* $ g++ -Wall -Wextra smart_dtor.cpp
*
* Run
*
* $ ./a.out
* make_shared<Base>
* ~Base()
*
* $ ./a.out Derived
* make_shared<Derived>
* ~Derived()
* ~Intermediate()
* ~Base()
*/
#include <iostream>
#include <memory>
struct Base
{
~Base()
{
std::cout << "~Base()" << std::endl;
}
};
struct Intermediate : Base
{
~Intermediate()
{
std::cout << "~Intermediate()" << std::endl;
}
};
struct Derived : Intermediate
{
~Derived()
{
std::cout << "~Derived()" << std::endl;
}
};
std::shared_ptr<Base> Factory (bool isBase)
{
if (isBase)
{
std::cout << "make_shared<Base>" << std::endl;
return std::make_shared<Base>();
}
else
{
std::cout << "make_shared<Derived>" << std::endl;
return std::make_shared<Derived>();
}
}
int main (int argc, char**)
{
std::shared_ptr<Base> p = Factory(argc % 2);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment