当前位置:网站首页>深拷贝和浅拷贝的区别
深拷贝和浅拷贝的区别
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
边栏推荐
- Understanding and use of tp50, tp90 and tp99
- [leetcode 67] sum of two binary numbers
- JDBC operation transaction
- 电机与拖动(戚金清版)学习整理
- Generate excel template (drop-down selection, multi-level linkage)
- Installation and usage skills of idea
- List segmentation best practices
- Supply chain service terms
- 9.Life, the Universe, and Everything
- SQL optimization best practices
猜你喜欢
Explain of MySQL optimization
Programming record - picture rotation function SciPy ndimage. Simple use and effect observation of rotate()
[leetcode 54] spiral matrix
Framework analysis 1 Introduction to system architecture
Understanding and installing MySQL
Why does the subscript of the array start from 0 instead of 1?
Addition, deletion, query and modification of data
Algèbre linéaire chapitre 1 - déterminants
線性代數第二章-矩陣及其運算
Guaba and Computational Geometry
随机推荐
Programming record - picture rotation function SciPy ndimage. Simple use and effect observation of rotate()
In depth understanding of the relationship between dncblevel and noise denoising in the paper
程序设计训练
Custom exception class
Customized communication between threads (reentrantlock)
2. Average length of words
Paper on Image Restoration - [red net, nips16] image restoration using very deep revolutionary encoder decoder networks wi
Common programming records - parser = argparse ArgumentParser()
IO multiplexing of 09 redis
Rust 的多线程安全引用 Arc
GNU EFI header file
The problem that the page will refresh automatically after clicking the submit button on the form is solved
ThreadLocal. Threadlocalmap analysis
Doomsday (simple computational geometry)
Problems and solutions of database migration
Generation of verification code
[leetcode 954] double pair array
POI and easyexcel exercises
Rust 中的 Cell 共享可变指针
Type conversion in C #