osg*_*sgx 6 c++ stl copy-constructor rule-of-three
什么是复杂对象的"最小框架"(必要的方法)(具有明确的malloced内部数据),我想要存储在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);
}
Run Code Online (Sandbox Code Playgroud)
给
*** glibc detected *** ./a.out: double free or corruption (fasttop): 0x0804b008 ***
Aborted
Run Code Online (Sandbox Code Playgroud)
在valgrind:
malloc/free: 2 allocs, 12 frees, 50 bytes allocated.
Run Code Online (Sandbox Code Playgroud)
更新:
这种对象的最小方法是:(基于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); }
};
Run Code Online (Sandbox Code Playgroud)
谢谢,sbi,https: //stackoverflow.com/users/140719/sbi
sbi*_*sbi 10
请注意,Charles完全回答了您的问题.
无论如何,根据规则三,你的类,有一个析构函数,也应该有一个复制构造函数和赋值运算符.
我是这样做的:
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);}
void swap(DoIt& rhs) {std::swap(a,rhs.a);}
DoIt& operator=(DoIt rhs) {swap(rhs); return *this;}
};
Run Code Online (Sandbox Code Playgroud)
您使用的所有类型必须是CopyConstructible和Assignable.
CopyConstructible对于一个类型T意味着如果t是a T或a const T那么表达式T(t)必须产生T与原始的等价物t; t.~T()必须有效(可访问的析构函数); 并且&t必须给的地址t作为[const] T*.
Assignable意味着,对于一个T,t和一个T值u,表达式t = u必须作出t相当于u和为类型T&.
请注意,所有这些要求都通过简单的内置类型和POD结构来满足.如果在析构函数或构造函数中执行任何非平凡的操作,则必须确保复制构造函数和复制赋值运算符保留等价语义.
| 归档时间: |
|
| 查看次数: |
1656 次 |
| 最近记录: |