gpt4 book ai didi

c++ - 如何在具有指向对象的指针数组的类中创建复制构造函数和析构函数,其中对象本身具有指向 int 的指针数组

转载 作者:行者123 更新时间:2023-11-30 01:39:08 25 4
gpt4 key购买 nike

在下面的代码中,我有一个 A 类,它有一个动态的整数数组。我有另一个 B 类,它有一个指向 A 类对象的指针数组。我已经为 A 类编写了复制构造函数。我需要为 B 类编写一个复制构造函数和析构函数,我尝试了各种方法但没有成功。

A类的定义:

class A {
public:
A::A(const A& other){
siz = other.siz;
c = other.c;
s = other.s;
e = other.e;
arr= new int[other.c];
memcpy(arr, other.arr, sizeof(int) * c);
}
A::~A() {
delete [] m_arr;
}

const A& operator=(const A& rhs){

if(this == &rhs)
return *this; // handling of self assignment

delete[] arr; // freeing previously used memory

arr = new int[rhs.c];
siz = rhs.siz;
c = rhs.c;
e = rhs.e;
s = rhs.s;

memcpy(m_arr, rhs.arr, sizeof(int) * c);
return *this;
}

private :
int *arr ;
int c ;
int siz ;
int s ;
int e ;
}

B类的定义:

 class B {

public:
B::B(const B& other){
// .......need help here
}

B::~B() {
//......need help here
}

private :
static const int constant = 7;
A * array[constant] ;
int x ;
int y ;
int z ;
}

感谢帮助

最佳答案

关键是将原始 owning 指针包装到 RAII 资源管理器 中,并定义组装这些安全 RAII 构建 block 的类。然后,C++ 编译器将能够自动合成复制操作和析构函数(以及移动操作)。

例如,在您的 class A你有一个int *arr数据成员,用于存储指向动态分配数组的拥有 原始指针。将其替换为 RAII 资源管理器,如标准 std::vector容器(例如 std::vector<int> arr )。

这样一来,就无需定义显式析构函数,因为编译器将自动调用 std::vector vector 数据成员上的析构函数,内存将自动释放(无需显式调用 delete[])。

类似地,默认复制构造函数将执行成员复制,因此 std::vector复制构造函数将被 C++ 编译器自动调用,并且从源 vector 到目标 vector 的深度复制将自动发生,无需您使用 new[] 来“重新发明轮子”动态分配,memcpy

从 C++11 开始,您可以告诉 C++ 编译器使用此语法合成默认复制构造函数(也可用于默认构造函数、移动构造函数、复制赋值运算符等)

class A {
public:
...
A(const A&) = default;

...
};

class B 也是如此, 而不是 A * array[constant]数据成员,考虑使用 vector ,例如指向 A 的智能指针 vector :

vector<shared_ptr<A>> arrayOfAs;

替代方法可能是使用 std::array 对于大小不变的东西。

无论如何,关键是:考虑使用 RAII 资源管理器作为更复杂类的构建 block ,而不是将原始拥有指针和其他不安全的原始资源作为数据成员。每个原始资源都应该安全地包装在自己的 RAII 资源管理器中,而这又应该用作更复杂类的数据成员。


P.S. 作为额外阅读,请考虑阅读 "What is The Rule of Three?" , 而这种 follow up .

关于c++ - 如何在具有指向对象的指针数组的类中创建复制构造函数和析构函数,其中对象本身具有指向 int 的指针数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46423735/

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