So i am trying to develop my understanding of shared_ptr and if multiple shared ptr point at the same resource shared pointer is resposible to handle the case where destrcutor should neve be called before the last pointer pointing at the resource is destroyed.
Here is my sample code:
#include <iostream>
#include <memory>
class A {
public:
A(int num) {
std::cout << "cons A\n";
}
~A() {
std::cout << "dis A\n";
}
};
int main() {
std::shared_ptr<A> ptr(new A(12));
{
std::cout << "Inside Scope \n";
std::shared_ptr<A> ptr1 = ptr;
std::cout << "Outside Scope \n";
}
std::shared_ptr<A> ptr2(ptr.get());
std::cout << ptr << std::endl;
}
And the output with exception being thrown is given below
cons A
Inside Scope
Outside Scope
dis A
dis A
free(): double free detected in tcache 2
Can anybody explain this behaviour or i am misreading anything ? Thanks in advance.