Let's see the following code:
#include <iostream>
#include <memory>
using namespace std;
class myClass{
public:
int a = 15;
myClass(int x): a(x){};
~myClass(){cout << "die die ";};
};
int main()
{
myClass* c;
{
std::shared_ptr<myClass> a = std::make_shared<myClass>(16);
cout<< a.use_count(); //1
std::shared_ptr<myClass> b = a;
cout<< a.use_count(); //2
c = a.get();
cout<< a.use_count(); // still 2
} // die die
cout << (*c).a; // 16? UB?
return 0;
}
We can notice that an instance of myClass
is created and is managed by a std::shared_ptr
. The count increases when a new shared pointer points to it which is normal. IT DOES NOT increase when a raw pointer c
starts pointing to it, which is also normal.
When the scope is closed at }
we can notice that the destructor was called. However we still have access to c
`s data. Also notice that the destructor was only called once.
Is this an undefined behavior? or was the instance copied at .get()
? If it was copied what happened with the destructor? delete
ing c
crashes (which in general proves how bad an idea this is).
For context, I'm working on a project that contains quite old code and raw pointers were mixed with boost and std's smart pointers, so I want to understand how to deal with this cases.
Edit
What about if I create a new instance and not a pointer?
int main()
{
myClass c(5);
{
std::shared_ptr<myClass> a = std::make_shared<myClass>(16);
cout<< a.use_count(); //1
std::shared_ptr<myClass> b = a;
cout<< a.use_count(); //2
c = *(a.get()); // This looks ugly, but am I getting a copy?
cout<< a.use_count(); // still 2
}// die die
cout << (c).a; //16
return 0;
}// die die
In this case the destructor was actaully called, is this a safe way to copy using .get()
?