Your function is a smart start:
vector<boost::shared_ptr<People>>& getPeople() const { for( vector<boost::weak_ptr<People>::iterator it = my_people.begin(); it != my_people.end(); ++it) { (*it).lock(); } return my_people; }
But calling (*it).lock() just creates shared_ptr and discards it, it does not change the type of vector elements, and you cannot return the vector as another type.
You need to create a vector of the desired type, fill it with shared_ptr objects and return it:
vector<boost::shared_ptr<People>> getPeople() const { vector<boost::shared_ptr<People>> people(my_people.size()); std::transform(my_people.begin(), my_people.end(), people.begin(), boost::bind(&boost::weak_ptr<People>::lock, _1)); return people; }
This my_people over each element of my_people , calls lock() on it, and assigns the result to the corresponding element people .
If you know that my_people never contains obsolete pointers, this is even simpler:
vector<boost::shared_ptr<People>> getPeople() const { vector<boost::shared_ptr<People>> people(my_people.begin(), my_people.end()); return people; }
This populates the people vector, creating each shared_ptr element from the weak_ptr element. The difference is that this version will throw an exception if weak_ptr expired, because the shared_ptr constructor throws if weak_ptr has expired. The version using transform will put the empty vector shared_ptr into the vector if the expired weak_ptr is converted.
source share