简体   繁体   中英

C++: Error when copying from *std::shared_ptr

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?

The problem is (almost certainly) that you're shallow-copying one of the members of MyObject in its copy constructor. Then you either try to access the shallow data that's no longer valid, or you double delete it.

Consider the cases: In the first and third cases, the very first object from which all copies are made is still alive when you act on the stack object. In the second case the shared_ptr goes away after the copy construction, invoking the destructor of MyObject .

If you changed the third case thusly, I suspect it would crash:

MyObject * obj_ptr2 = new MyObject("hello");
MyObject obj3 = *obj_ptr2;
delete obj_ptr2;
obj3.print();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM