背景
A对象内部属性a属于int ,动态分配内存回收,析构函数delete
A ** aptr = new A[10] 申请10个空间长度的A*类型
测试浅拷贝
测试代码
#include<iostream>
using namespace std;
class A{
public:
int* a;
A(int i){ //构造函数
a = new int(i) ;
}
~A(){ //析构函数
cout<<"~A() i = "<<*(this->a)<<endl;
if(a!= nullptr){
delete a;
a= nullptr;
}
}
};
//二级指针的空间申请与分配
void test(){
int len = 10;
A ** aptr = new A*[len]; //申请10个空间为A*类型指针空间
for(int i = 0; i < len; i++){
aptr[i] = new A(i); //为每个指针申请空间
}
//先释放A*
for (int i = 0; i < len; ++i) {
delete aptr[i];
}
//再释放A**
delete [] aptr;
}
//指针拷贝
void test_copy_ptrArr(){
int len = 10;
A ** aptr = new A*[len]; //申请10个空间为A*类型指针空间
for(int i = 0; i < len; i++){
aptr[i] = new A(i); //为每个指针申请空间
}
//拷贝(浅拷贝)
A ** bptr = new A*[len];
for (int i = 0; i < len; i++) {
bptr[i] = aptr[i];// 属于浅拷贝
}
//打印地址查看
for (int i = 0; i < len; ++i) {
cout<<"aptr["<<i<<"] = "<<aptr[i]<<endl;
cout<<"bptr["<<i<<"] = "<<bptr[i]<<endl; //两者打印的是一样
}
// delete[] aptr; //释放的是aptr,*aptr没有释放,可能会出现内存溢出
// for (int i = 0; i < len; ++i) {
// cout<<"aptr["<<i<<"] = "<<*(aptr[i]->a)<<endl;
// cout<<"bptr["<<i<<"] = "<<*(bptr[i]->a)<<endl;
// }
//完整释放(拷贝后释放)
for (int i = 0; i < len; ++i) {
delete bptr[i]; // 会调用~A()析构函数
}
delete[] bptr;
delete[] aptr;
}
int main()
{
// test();
test_copy_ptrArr();
return 0;
}
标签:10,int,C++,析构,new,拷贝,指针
From: https://www.cnblogs.com/paylove/p/18311700