什么是复杂对象的“最小框架”(必要的方法)(具有显式的malloced内部数据),我想将其存储在STL容器中,例如<载体GT ;?
对于我的假设(复杂对象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); }
- };
解决方法
请注意,查尔斯完美地拥有
answered your question.
无论如何,根据Rule of Three,你的类有一个析构函数,也应该有一个复制构造函数和赋值运算符.
我是这样做的:
- 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,a);}
- void swap(DoIt& rhs) {std::swap(a,rhs.a);}
- DoIt& operator=(DoIt rhs) {swap(rhs); return *this;}
- };