我目前正在做一个大项目,我需要使用weak_ptr
而不是shared_ptr
。拥有一个weak_ptr向量,想要返回一个向量shared_ptr
这是我的问题。
我有一个名为House的类,属性为:vector<boost::shared_ptr<People>> my_people
。 我想修改这个数据成员为vector<boost::weak_ptr<People>> my_people
。
我的吸气剂
vector<boost::shared_ptr<People>>& getPeople() const
{
return my_people;
}
通常情况下,用一个简单的weak_ptr
我可以返回my_people.lock();
但我有一个载体,我不知道该怎么做这样的事情:
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;
}
换句话说,我想返回我的weak_ptr
的矢量,但是作为shared_ptr
的矢量。可能吗?或者我必须返回矢量weak_ptr
并在我使用它们的任何地方使用lock()
?
你真的需要'weak_ptr'摆在首位? –