Boost Shared_Ptr appointment

Why can't I 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 to do it instead?

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

  QueuList li; QueuList lis; li.SetNextPtr(&lis); 

When the core goes beyond, I get a debug statement ... Any ideas

+6
c ++ pointers boost
source share
3 answers

Placing the pointer inside shared_ptr transfers ownership of the pointer to shared_ptr, so shared_ptr is responsible for removing it. This is a conceptually important operation, so the shared_ptr developers did not want this to just happen as part of its normal form. For example, they wanted to prevent code such as:

 some_shared_ptr = some_other_smart_pointer.get(); 

which looks pretty innocuous, but would mean that both smart pointers believed that they were responsible for clearing the pointer and probably deleting the pointer twice or something like that.

This is what happens with your debug statement. A call to SetNextPtr(&lis) transfers ownership of &lis to shared_ptr , and โ€œownershipโ€ means that shared_ptr will call delete on its pointer when the last copy of shared_ptr is out of scope. That way, you are actually deleting the local (stack) variable - lis - which corrupts the stack and causes a crash.

+5
source share

This is done to prevent the accidental assignment of pointers to shared_ptr , whose lifetime management is independent. You must explicitly create shared_ptr , which will then own the object.

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

Change about change . The problem is that in your case shared_ptr goes into the ownership of the object on the stack. Then two things can happen:

  • The stack stack of the object is cleared before shared_ptr reaches the reference count of 0. In this case, shared_ptr will try to remove the nonexistent object somewhere later, which will lead to undefined behavior.
  • shared_ptr reaches reference count 0 before the stack stack is cleared. In this case, it will try to delete the object on the stack. I donโ€™t know exactly what will happen in this case, but I would suggest that this behavior is undefined.
+7
source share

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

 next.Reset(Next); 
+6
source share

All Articles