我的std :: vector应该包含指针还是结构?

Joh*_*ohn 8 c++ memory-management reference vector

我知道持有指针会产生额外的解除引用操作的开销,但它会省去包括(可能很大的)包含我的struct定义的头文件.

但是,我的偏好取决于拥有std::vector<myStruct> *ptr2Vect会员的优势.即,不必在每个元素上调用delete.这有多大的性能优势?矢量真的可以在堆栈上分配对象吗?我对模板类相当新,并想知道动态数组是否有可能在堆栈上以及以什么价格进行扩展?

_ 编辑 _

我无法理解默认的复制构造函数和operator =成员,并试图将事物保持为简单的结构.我没有明确定义实现,因此担心将vector元素设置为对象而不是指针将在赋值时创建临时对象,这将被破坏并因此破坏其副本.

_ 编辑 _

很抱歉延迟提供相关信息(我对代码很害羞).

我想调用push_back(newObj).现在,如果我不使用指针,我有一个很大的问题,因为我不想执行深度复制,但我的dtor将释放LHS和RHS共享的复制构造函数调用的内存.

Fle*_*exo 8

作为一般的经验法则,我会说你可能不想在你的容器中加上指针,除非有充分的理由.

考虑指针的可能原因:

  • 你有virtual功能
  • 你有一个类层次结构
  • 你不知道你正在使用它们的对象的大小.(在这种情况下,您只能使用指针或引用,并且您不能使用引用向量)
  • 你的对象非常大(可能以此为基准)

不将指针放在容器中的最大原因是它可以容易地避免错误并意外泄漏内存.当您开始考虑异常时尤其如此.

在容器中没有指针使得使用STL变得更加容易<algorithms>,请考虑:

#include <vector>
#include <string>
#include <iostream>
#include <iterator>
#include <algorithm>

int main() {
  std::vector<std::string> test;
  test.push_back("hello world");
  std::copy(test.begin(), test.end(), 
            std::ostream_iterator<std::string>(std::cout, "\n"));
}
Run Code Online (Sandbox Code Playgroud)

与:

#include <vector>
#include <string>
#include <iostream>
#include <iterator>
#include <algorithm>

int main() {
  std::vector<std::string*> test;
  // if push_back throws then this will leak:
  test.push_back(new std::string("hello world"));
  // Can't do:
  std::copy(test.begin(), test.end(), 
            std::ostream_iterator<std::string>(std::cout, "\n"));
  // Will now leak too
}
Run Code Online (Sandbox Code Playgroud)

(我永远不会这样做)

或者可能:

#include <vector>
#include <string>
#include <iostream>
#include <iterator>
#include <algorithm>

int main() {
  std::vector<std::string*> test;
  std::string str("hello world");
  test.push_back(&str);
  // Can't do:
  std::copy(test.begin(), test.end(), std::ostream_iterator<std::string>(std::cout, "\n"));
}
Run Code Online (Sandbox Code Playgroud)

但是这个语义让我感到不舒服 - 根本不清楚delete代码中的其他地方是非常糟糕的事情,即使没有泄漏问题,你仍然不能非常舒服地使用STL算法.