When I run this code:
#include <iostream> #include <memory> struct Adaptee { int value = 0; }; class Adapter { private: Adaptee* adaptee; public: Adapter (Adaptee* a) : adaptee(a) {} void increaseValueByOne() {adaptee->value++;} }; int main() { Adaptee* a = new Adaptee; Adapter* adapter = new Adapter(a); adapter->increaseValueByOne(); delete adapter; std::cout << "a->value = " << a->value << std::endl; } I get the output: a->value = 1. But when I run this:
struct Adaptee { int value = 0; }; class Adapter { private: std::shared_ptr<Adaptee> adaptee; public: Adapter (Adaptee* a) : adaptee (std::shared_ptr<Adaptee>(a)) {} void increaseValueByOne() {adaptee->value++;} }; int main() { Adaptee* a = new Adaptee; Adapter* adapter = new Adapter(a); adapter->increaseValueByOne(); delete adapter; std::cout << "a->value = " << a->value << std::endl; } I get: a->value = 7738248
Why is this? Isn't the use_count of adapter->adaptee simply changing from 2 to 1, so nothing should go wrong? When I remove the line 'delete adapter;' everything is fine though, but then there is leaking.
Adapter adapter{new Adaptee};you wouldn't be able to get this odd behavior.Adapterat least partial ownership of theAdapteeobject. When Adapter dies, it deallocated the object it points to. When you mix shared pointers withdeleteyou're on your own, that's not how the library is suppose to be used.delete adapter.