【发布时间】:2016-03-11 10:01:45
【问题描述】:
我处于一种相当特殊的情况,需要我使用原始指针向量作为类成员:
- 我需要保留一个抽象对象列表 (I understood I could not use
vector<AbstractClass>directly)。 - 我不能使用 Boost 或 std::tr1,所以没有智能指针库(因为我正在使用的硬件的限制)。
这是我需要的基本示例:
#include <vector>
class Foo
{
virtual void foo() {}
};
class Bar : public Foo
{
void foo(){}
};
class FooBar
{
vector<Foo*> list;
void add(){ list.push_back(new Bar()); }
};
来自 Java,我非常害怕指针和内存泄漏。 This post 最初建议在对象超出范围时手动删除对象。在FooBar的析构函数中这样做就够了吗?
class FooBar
{
vector<Foo*> list;
void add(){ list.push_back(new Bar()); }
~FooBar(){
for(vector<Foo*>::iterator it=list.begin(); it!=list.end(); it++)
delete *it;
}
};
通过rule of three,我想我还必须实现一个复制构造函数和一个赋值运算符。以下(基于this 和that 帖子)是正确的实现吗?
FooBar::FooBar(const FooBar& orig) : list(orig.list.size()) {
try {
vector<Foo*>::iterator thisit = list.begin();
vector<Foo*>::const_iterator thatit = orig.list.cbegin();
for (; thatit != orig.list.cend(); ++thisit, ++thatit)
*thisit = *thatit; // I'm okay with a shallow copy
} catch (...) {
for (vector<Foo*>::iterator i = list.begin(); i != list.end(); ++i)
if (!*i)
break;
else
delete *i;
throw;
}
}
FooBar& operator=(const FooBar& orig){
FooBar tmp(orig);
swap(tmp);
return *this;
}
【问题讨论】:
-
// I'm okay with a shallow copy这与析构函数的实现一起将打破你的脖子。您将尝试释放多次分配的空间。 -
无法理解“没有智能指针库”。您可以随时从智能指针获取原始指针。
-
为什么是 try/catch?抛出什么?
-
@πάνταῥεῖ,那么是析构函数错误还是复制构造函数错误?
-
如果
no smart pointer library (because of constraints from the hardware I'm using).然后编写您自己的简单共享智能指针并计算链接。没有想象中那么难。您当前的代码(复制方法)将泄漏内存