Tony The Lion
Tony The Lion

Reputation: 63190

Boost Shared_Ptr assignment

Why can I not do this?

boost::shared_ptr<QueuList> next;

void QueuList::SetNextPtr(QueuList* Next)
{
    boost::mutex mtx;

    boost::mutex::scoped_lock lock(mtx);
    {// scope of lock
        //if (next == NULL)  // is this needed on a shared_ptr??
        next = Next;  // Why can I not assign a raw ptr to a shared_ptr????
    }

}

How should I do it instead??

EDIT: Calling this method when the next variable is assigned properly, it still causes an error when the QueuList object is destroyed for some reason. I get a debug assertion. The destructor of the object does nothing in particular. It only crashes when I call this function:

    QueuList li;
    QueuList lis;

    li.SetNextPtr(&lis);

When main goes out of scope, I get a debug assertion... Any ideas??

Upvotes: 6

Views: 12744

Answers (3)

Mark Ingram
Mark Ingram

Reputation: 73585

You can use the Reset() function rather than the wordier next = boost::shared_ptr<QueueList>(Next);

next.Reset(Next);

Upvotes: 6

Bj&#246;rn Pollex
Bj&#246;rn Pollex

Reputation: 76778

This is done to prevent accidentally assigning pointers to a shared_ptr whose lifetime is managed independently. You have to explicitly create a shared_ptr that then takes ownership of the object.

next = boost::shared_ptr<QueueList>( Next );

Edit about your edit The problem is that in your case the shared_ptr takes ownership of an object on the stack. Then two things can happen:

  1. The stack-frame of the object gets cleared before the shared_ptr reaches a reference count of 0. In that case, the shared_ptr will try to delete a non-existing object somewhere later, leading to undefined behavior.
  2. The shared_ptr reaches a reference count of 0 before the stack-frame is cleared. In that case, it will try to delete an object on the stack. I do not know exactly what happens in that case, but I would assume that it is undefined behavior too.

Upvotes: 7

Doug
Doug

Reputation: 9100

Putting a pointer inside a shared_ptr transfers ownership of the pointer to the shared_ptr, so the shared_ptr is responsible for deleting it. This is conceptually an important operation, so the designers of shared_ptr didn't want it to just happen as part of a normal-looking assignment. For example, they wanted to prevent code like:

some_shared_ptr = some_other_smart_pointer.get();

which looks fairly innocuous, but would mean that both smart pointers thought they had responsibility for cleaning up the pointer, and would likely double-delete the pointer or something similar.

This is what's happening with your debug assertion. Calling SetNextPtr(&lis) passes ownership of &lis to the shared_ptr, and "ownership" means that the shared_ptr will call delete on its pointee when the last copy of the shared_ptr goes out of scope. So you're effectively deleting a local (stack) variable - lis - which corrupts the stack and causes the crash.

Upvotes: 5

Related Questions