作为一般经验法则,我会说您可能不想将指针放入容器中,除非有充分的理由。
考虑指针的可能原因:
- 你有
virtual
功能
- 你有一个类层次结构
- 您不知道使用它们的对象的大小。 (在这种情况下,您只能使用指针或引用,并且不能拥有引用向量)
- 您的对象非常大(可能对此进行基准测试)
不将指针放入容器的最大原因是它使得它much更容易不犯错误和意外泄漏内存。当您开始考虑例外情况时尤其如此。
容器中没有指针使得使用 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"));
}
Versus:
#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
}
(我会never do)
或者可能:
#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 算法。