-
-
Save olibre/90dc7cb3d47b6d57defc99191dffc39c to your computer and use it in GitHub Desktop.
Smart destructor
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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