0

i am new to boost::shared_ptr using it the first time now. I have a std::vector containing boost::shared_ptr which i "filled" with objects created from a custom class.

In Code: std::vector<boost::shared_ptr<Foo>> data;

The vector is created inside a function on the stack. I want to access some elements inside my vector using vector.at(k). The retured shared_ptr will be send to another thread, lets call him T1. My vector runs out of scope while T1 is still processing the shared_ptr.

In Code:

void myFunction(){

   //lets get my object
   boost::shared_ptr<Foo> obj = data.at(k);

   //emit it to Thread T1 (i am using QT)
   emit sendObjToThread1(obj);

}

I previously thought this would give no problem, but since my program is acting very strange, i am about to changing my mind. :) To clarify this i am asking you on this platform now. :)

Is it right, that my object will be destroyed if my vector runs out of scope? If yes, how can i manage to get a deep copy of the shared_ptr (but not the object it holds). Just to have mentioned it: My application is based on QT.

Thx for reading.

3 Answers 3

2

No. It returns a reference.

boost::shared_ptr<Foo> obj = data.at(k);

But in this statement you are making a copy by creating obj.

boost::shared_ptr<Foo>& obj = data.at(k);
                     ^^^

Now there are no copies made.

Edit:

What about this line?

sendObjToThread1(obj);

Are you passing be reference or value? If you pass by reference to another thread then this is a problem as the local copy of obj is about to die (as soon as the function returns). So you must pass obj by value to make sure the other thread has its own copy and increments the shared_pointer counter appropriately.

1
  • Ok, thank you. So the problem for the strange behaviour of my program is somewhere else. :D
    – Handsan
    Mar 5, 2011 at 0:05
2

See one of the docs for std::vector<T>::at(). It returns a reference. As long as your emit sendObjToThread1(obj); does a copy of the shared_ptr you are safe.

1
  • 1
    Correctness is independent of what emit does, as obj is already a copy of the referenced object (no & in the declaration) Mar 4, 2011 at 20:51
0

I think you're using threads. Go read this and double-check everything related to thread safety. Make sure you're using either the pthreads or lock-free implementation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.