当前位置:网站首页>深拷贝和浅拷贝的区别
深拷贝和浅拷贝的区别
2022-04-23 05:46:00 【OceanKeeper1215】
默认拷贝构造可以完成对象的数据成员简单的赋值,这就是浅拷贝。
对象的数据资源是由指针指向的堆时,默认的拷贝构造函数只是将指针复制。
但是之后释放的时候,会释放两次,即同一个内存地址被释放了两次,会产生错误。
深拷贝是指,程序员自己重新写一份拷贝构造,在调用拷贝构造的时候,编译器优先调用程序员手写的拷贝构造,在程序员写的拷贝构造中,可以单独开辟一块内存空间用来保存数据,这就是深拷贝。
class Test
{
private:
int* p;
public:
Test(int x)
{
this->p=new int(x);
cout << "对象被创建" << endl;
}
~Test()
{
if (p != NULL)
{
delete p;
}
cout << "对象被释放" << endl;
}
int getX() { return *p; }
//深拷贝(拷贝构造函数)
Test(const Test& a)
{
this->p = new int(*a.p);
cout << "对象被创建" << endl;
}
//浅拷贝(拷贝构造函数)
//Test(const Test& a)
//{
// this->p = a.p;
// cout << "对象被创建" << endl;
//}
};
int main()
{
Test a(10);
//我们手动的写拷贝构造函数,C++编译器会调用我们手动写的
Test b = a;
return 0;
}
版权声明
本文为[OceanKeeper1215]所创,转载请带上原文链接,感谢
https://blog.csdn.net/OceanKeeper1215/article/details/120978438
边栏推荐
猜你喜欢

Detection technology and principle
![Unsupervised denoising - [tmi2022] ISCL: dependent self cooperative learning for unpaired image denoising](/img/cd/10793445e6867eeee613b6ba4b85cf.png)
Unsupervised denoising - [tmi2022] ISCL: dependent self cooperative learning for unpaired image denoising

How SYSTEMd uses / etc / init D script

Motor and drive (Qi Jinqing Edition)
![[leetcode 67] sum of two binary numbers](/img/91/afdd8197ca44ee910e2ee490929df1.png)
[leetcode 67] sum of two binary numbers

Programming record - picture rotation function SciPy ndimage. Simple use and effect observation of rotate()

lambda expressions

Explain of MySQL optimization

Generate excel template (drop-down selection, multi-level linkage)
![Denoising paper - [noise2void, cvpr19] noise2void learning denoising from single noise images](/img/9d/487c77b5d25d3e37fb629164c804e2.png)
Denoising paper - [noise2void, cvpr19] noise2void learning denoising from single noise images
随机推荐
Mysql database foundation
C3p0 database connection pool usage
Linear algebra Chapter 1 - determinant
POI and easyexcel exercises
Rust 中的 Cell 共享可变指针
Fact final variable and final variable
Addition, deletion, query and modification of data
[leetcode217] there are duplicate elements
List segmentation best practices
Robocode教程3——Robo机器剖析
[leetcode 202] happy number
Contrôle automatique (version Han min)
C # Foundation
檢測技術與原理
Chapter 4 of line generation - linear correlation of vector systems
Doomsday (simple computational geometry)
程序设计训练
[leetcode 54] spiral matrix
Three ways to create threads
A general U-shaped transformer for image restoration