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??
Putting a pointer inside a
shared_ptrtransfers ownership of the pointer to the shared_ptr, so theshared_ptris responsible for deleting it. This is conceptually an important operation, so the designers ofshared_ptrdidn’t want it to just happen as part of a normal-looking assignment. For example, they wanted to prevent code like: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&listo theshared_ptr, and “ownership” means that theshared_ptrwill calldeleteon its pointee when the last copy of theshared_ptrgoes out of scope. So you’re effectively deleting a local (stack) variable –lis– which corrupts the stack and causes the crash.