Skip to content

Instantly share code, notes, and snippets.

@root42
Created November 14, 2019 09:19
Show Gist options
  • Save root42/58b31d95f94beb1808162283f93990ef to your computer and use it in GitHub Desktop.
Save root42/58b31d95f94beb1808162283f93990ef to your computer and use it in GitHub Desktop.
Destructors when using shared_ptr assignments
#include <iostream>
#include <memory>
class Base
{
public:
Base() { std::cout << "Base constructor" << std::endl; }
virtual ~Base() { std::cout << "Base destructor" << std::endl; }
};
class DerivedA : public Base
{
public:
DerivedA() { std::cout << "A constructor" << std::endl; }
virtual ~DerivedA() { std::cout << "A destructor" << std::endl; }
};
class DerivedB : public Base
{
public:
DerivedB() { std::cout << "B constructor" << std::endl; }
virtual ~DerivedB() { std::cout << "B destructor" << std::endl; }
};
int main()
{
std::shared_ptr< Base > ptr( new DerivedA );
std::cout << "Assignment: " << std::endl;
ptr.reset( new DerivedB );
std::cout << "Done." << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment