gpt4 book ai didi

c++ - 在 STL vector 中存储对象 - 最少的方法集

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:07:49 24 4
gpt4 key购买 nike

什么是复杂对象(具有显式分配的内部数据)的“最小框架”(必要方法),我想将其存储在 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); }
};

谢谢,履行机构,https://stackoverflow.com/users/140719/sbi

最佳答案

注意 Charles 有 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,rhs.a+10,a);}
void swap(DoIt& rhs) {std::swap(a,rhs.a);}
DoIt& operator=(DoIt rhs) {swap(rhs); return *this;}
};

关于c++ - 在 STL vector 中存储对象 - 最少的方法集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2501171/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com