c ++ 11成员函数从unique_ptr的向量返回原始指针的向量 [英] c++11 member function returns vector of raw pointers from vector of unique_ptr
问题描述
我开始使用c ++ 11的功能,我喜欢使用智能指针只拥有对象。这是我的类:
I am starting using c++11 features and I like to use smart pointers only to own the objects. Here is my class:
class MyClass {
public:
vector<MyObject*> get_objs() const;
private:
vector<unique_ptr<MyObject>> m_objs;
};
语义是 MyClass
通过 make_unique
()创建的 MyObject
get_objs()
返回一个原始指针向量,以便各种调用者更新对象。因为这些调用方不拥有对象,所以函数不返回 vector< unique_ptr>。
The semantics is that MyClass
owns a serial of MyObject
which are created through make_unique
(). get_objs()
returns a vector of raw pointers in order for various callers to update the objects. Because those callers do not own the objects, so the function does not return vector<unique_ptr>.
意味着我需要像这样实现 get_objs()
:
But this means I need to implement get_objs()
like this:
vector<MyObjects*> MyClass::get_objs() const
{
vector<MyObjects*> ret;
for (auto obj : my_objs) {
ret.push_back(obj->get());
}
return ret;
}
我的关注是 get_objs $ c>经常被调用,每次都有一个开销来构造这个原始指针向量。
My concern is get_objs()
is called fairly often, each time there is an overhead to construct this raw pointer vector.
有什么我可以在这里做吗?如果没有c ++ 11的技巧来节省开销,我应该使用 vector< MyObject *>
为 m_objs
首先?
Is there something I could do here? If there is no c++11 tricks to save the overhead, should I just use type vector<MyObject*>
for m_objs
in the first place?
UPDATE 1
Jonathan Wakely使用 operator []
的解决方案改进了我的工作,使得调用者可以直接访问单个对象。
Jonathan Wakely's solution using operator[]
improves mine so that caller can access individual object directly.
有没有其他解决方案?我不介意去所有调用 get_objs(),
的地方,但想看看是否有更好的解决方案。
Is there any other solution? I do not mind go over all the places calling get_objs(),
but like to see if there is even better solution.
另一个注意事项 - 我不能使用BOOST,只是一些限制我必须与之生活。
Another note - I cannot use BOOST, just some restriction I have to live with.
推荐答案
class MyClass {
public:
std::vector<std::unique_ptr<MyObject>> const& get_objs() const {
return m_objs;
}
private:
std::vector<std::unique_ptr<MyObject>> m_objs;
};
a const std :: unique_ptr< MyObject>&
不能窃取所有权,并且不同于 std :: unique_ptr< const MyObject>
。 const std :: vector< std :: unique_ptr< MyObject>&
只能授予 const
其数据。
a const std::unique_ptr<MyObject>&
cannot steal ownership, and is not the same as a std::unique_ptr<const MyObject>
. A const std::vector<std::unique_ptr<MyObject>>&
can only grant const
access to its data.
这篇关于c ++ 11成员函数从unique_ptr的向量返回原始指针的向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!