I have a function that returns a shared pointer to an object (it is difficult to include the MyObject definition because of many large dependencies):
std::shared_ptr<MyObject> f(std::string params)
{
return std::shared_ptr<MyObject>(new MyObject(params));
}
Does anyone know why this code works:
Case 1: no errors with valgrind -v --tool=memcheck
std::shared_ptr<MyObject> obj_ptr = f("hello");
MyObject obj = *obj_ptr;
While this code crashes:
Case 2: crashes and gives several errors with valgrind -v --tool=memcheck
MyObject obj = *f("hello");
The MyObject class has a working assignment operator and copy constructor (both verified in Case 1).
I have also tried creating a std::shared_ptr<MyObject>
(via f
), copying that to a pointer, copying the pointer to an object on the stack, and deleting the pointer. The final object on the stack is still fine:
Case 3: no errors with valgrind -v --tool=memcheck
std::shared_ptr<MyObject> obj_ptr = f("hello");
MyObject * obj_ptr2 = new MyObject(*obj_ptr);
MyObject obj3 = *obj_ptr2;
delete obj_ptr2;
obj3.print();
Is the error perhaps because std::shared_ptr
is created as an rvalue, and frees its memory as soon as the *
operator runs?