什么是复杂对象(具有显式分配的内部数据)的“最小框架”(必要方法),我想将其存储在 STL 容器中,例如<vector>
?
对于我的假设(复杂对象 Doit 的示例):
#include <vector>
#include <cstring>
using namespace std;
class Doit {
private:
char *a;
public:
Doit(){a=(char*)malloc(10);}
~Doit(){free(a);}
};
int main(){
vector<Doit> v(10);
}
给
*** glibc detected *** ./a.out: double free or corruption (fasttop): 0x0804b008 ***
Aborted
在 valgrind 中:
malloc/free: 2 allocs, 12 frees, 50 bytes allocated.
更新:
此类对象的最小方法是:(基于 sbi 答案)
class DoIt{
private:
char *a;
public:
DoIt() { a=new char[10]; }
~DoIt() { delete[] a; }
DoIt(const DoIt& rhs) { a=new char[10]; std::copy(rhs.a,rhs.a+10,a); }
DoIt& operator=(const DoIt& rhs) { DoIt tmp(rhs); swap(tmp); return *this;}
void swap(DoIt& rhs) { std::swap(a,rhs.a); }
};