7

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. C has two functions that add or remove objects in m_MyList. m_MyList should also be made accessible for consumers of C as they need to read the collection of MyClass objects. The external reader of the collection will have no means to change the collection, thus the MyClass objects are owned only by C.

Now my question: In C++11 style, what is the best T to store in the vector? 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
4

2 回答 2

13

如果MyClass对象由 拥有C,那么最好的选择是最简单的:

std::vector<MyClass>

我可以看到在这里使用的唯一原因std::unique_ptrs是如果您需要保留指向基类的指针以实现多态性。在这种情况下,unique_ptrs 用于在向量销毁时释放资源。但是C接口不应该将所有权转移给客户端。

于 2012-05-31T08:19:10.993 回答
12

std::vector<MyClass*>如果 C 拥有对象,则原始指针 ( ) 不正确。其他两个与以下权衡非常相似:

  • std::vector<MyClass>- 要求 MyClass 是可复制和/或可移动的
  • std::vector<unique_ptr<MyClass>>- 需要(额外的)动态分配

在容器上执行的操作类型也可能是相关的。举一个极端的例子,如果 MyClass 很大并且容器被反复洗牌,unique_ptr那将是更好的选择。

于 2012-05-31T08:21:54.220 回答