[英]Should I use std::unique_ptr<T> in a std::vector member variable in my class?
Imagine a class C
that has a member variable m_MyList
of type std::vector
in which I want to store objects of type MyClass
. 想象一个
class C
,它有一个类型为std::vector
的成员变量m_MyList
,我想在其中存储MyClass
类型的对象。 C
has two functions that add or remove objects in m_MyList
. C
有两个函数可以在m_MyList
中添加或删除对象。 m_MyList
should also be made accessible for consumers of C
as they need to read the collection of MyClass
objects. 对于
C
消费者, m_MyList
也应该是可访问的,因为他们需要读取MyClass
对象的集合。 The external reader of the collection will have no means to change the collection, thus the MyClass
objects are owned only by C
. 集合的外部阅读器无法更改集合,因此
MyClass
对象仅由C
拥有。
Now my question: In C++11 style, what is the best T to store in the vector? 现在我的问题是:在C ++ 11风格中,向量中存储的最佳T是什么? The possibilities seem to be:
可能性似乎是:
std::vector<MyClass>
std::vector<MyClass*>
std::vector<unique_ptr<MyClass>>
, using std:move
to push the unique_ptr
into the vector
std::vector<unique_ptr<MyClass>>
,使用std:move
将unique_ptr
推送到vector
If the MyClass
objects are owned by C
, then the best option would be the simplest: 如果
MyClass
对象归C
,那么最好的选择是最简单的:
std::vector<MyClass>
The only reason I could see for using std::unique_ptrs
here is if you need to keep pointers to a base class for polymorphism. 我在这里看到使用
std::unique_ptrs
的唯一原因是你需要保持指向多态的基类的指针。 In this case the unique_ptrs serve the purpose of releasing resources upon destruction of the vector. 在这种情况下,unique_ptrs用于在向量被破坏时释放资源。 But then the
C
interface should not transfer ownership to the clients. 但是
C
接口不应该将所有权转移给客户端。
Raw pointers ( std::vector<MyClass*>
) are incorrect if C owns the objects. 如果C拥有对象,则原始指针(
std::vector<MyClass*>
)不正确。 The other two are pretty similar with the following trade-offs: 其他两个非常相似,具有以下权衡:
std::vector<MyClass>
- requires MyClass to be copyable and/or move-able std::vector<MyClass>
- 要求MyClass可以复制和/或移动 std::vector<unique_ptr<MyClass>>
- requires (additional) dynamic allocations std::vector<unique_ptr<MyClass>>
- 需要(额外的)动态分配 The kind of operations being performed on the container may also be relevant. 在容器上执行的操作类型也可能是相关的。 To take an extreme example, if MyClass is large and the container is being repeatedly shuffled,
unique_ptr
would be the better choice. 举一个极端的例子,如果MyClass很大并且容器被重复洗牌,那么
unique_ptr
将是更好的选择。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.