我知道持有指针会导致额外的取消引用操作的开销,但它可以节省我的时间,包括包含我的结构定义的(可能很大的)头文件。
然而,我的偏好取决于拥有 std::vector<myStruct> *ptr2Vect
的优势。成员。即,不必在每个元素上调用 delete。这是多大的性能优势? vector真的可以在栈上分配对象吗?我对模板类还很陌生,想知道动态数组是否有可能在堆栈上扩展,价格是多少?
_编辑_
我无法理解默认的复制构造函数和 operator= 成员,并试图将其保持为简单的结构。我没有明确定义任何实现,所以担心将 vector 元素设为对象而不是指针会在分配时创建临时对象,该对象将被破坏并因此破坏其拷贝。
_编辑_
很抱歉延迟提供相关信息(我对我的代码很害羞)。
我想调用 push_back(newObj)。现在,如果我不使用指针,我会遇到一个大问题,因为我不想执行深度复制,但我的 dtor 将释放此复制构造函数调用的 LHS 和 RHS 共享的内存。
最佳答案
根据一般经验,我会说您可能不想在容器中放置指针,除非有充分的理由。
考虑指针的可能原因:
- 你有
virtual
职能 - 你有一个类层次结构
- 您不知道您正在使用它们的对象的大小。 (在那种情况下你只能使用指针或引用,你不能有引用 vector )
- 您的对象非常大(可能是基准测试)
不将指针放在容器中的最大原因是它大大更容易避免出错和意外泄漏内存。当您开始考虑异常时尤其如此。
在容器中没有指针使得使用 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"));
}
对比:
#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
}
(我永远不会这样做)
或者可能:
#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"));
}
但是这个的语义让我感到不舒服 - 一点都不清楚 delete
代码中的其他地方将是一件非常糟糕的事情,即使没有泄漏问题,您仍然不能非常舒适地使用 STL 算法。
关于c++ - 我的 std::vector 应该包含指针还是结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7217611/