我有一个像下面这样的类:
class A {
SuperHugeClass* s;
public:
A(){ s = new SuperHugeClass(); }
};
因为SuperHugeClass
占用大量内存,我对默认构造函数和赋值运算符提供的浅拷贝没问题。但是,我也不想泄漏内存,所以我需要delete s
,但我必须小心它,否则我会多次删除它。
一种方法是通过s
如下引用计数:
class A {
int* refcount;
SuperHugeClass* s;
public:
A(){
refcount = new int(1);
s = new SuperHugeClass();
}
A(const A& other) : refcount(other.refcount), s(other.s) {
(*refcount)++;
}
~A() {
(*refcount)--;
if (!(*refcount)) {
delete refcount;
delete s;
}
}
friend void swap(const A& a, const A& aa) {
std::swap(a.refcount, aa.refcount);
std::swap(a.s, aa.s);
}
A& operator=(A other) {
swap(*this, other);
return (*this);
}
};
这是我第一次需要做这样的事情,但在我看来这应该是相当标准的,所以应该有一个“规范”的解决方案。有没有其他方法可以做到这一点?谢谢!