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.
No. It returns a reference.
But in this statement you are making a copy by creating obj.
Now there are no copies made.
Edit:
What about this line?
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.