shallow copy and deep copy

shallow copy and deep copy(浅拷贝与深拷贝)

C++03性能上长期被诟病的原因有一点就是其耗时且不必要的深度拷贝。

简单的理解就是浅拷贝就是拷贝指针,深拷贝就是重新分配内存拷贝数据

  • The default copy constructor     and default assignment operators do shallow copies, which is fine for     classes that contain no dynamically allocated variables.
  • Classes with dynamically     allocated variables need to have a copy constructor and assignment     operator that do a deep copy.
  • The assignment operator is     usually implemented using the same code as the copy constructor, but it     checks for self-assignment, returns *this, and deallocates any previously     allocated memory before deep copying.
  • If you don’t want a class to     be copyable, use a private copy constructor and assignment operator     prototype in the class header.

1.      默认拷贝构造或者默认赋值操作执行的浅拷贝,主要用于没有包含动态分配内存的类

2.      有动态内存分配的类则不能使用某人拷贝构造或者默认的赋值操作,并且需要执行深拷贝

3.      赋值操作和拷贝构造代码相同,但是多了检查self-assignment,返回*this,以及释放前面分配的内存。

4.      如果不希望该类可以拷贝,则使用private类型的拷贝构造和赋值操作

 

考考资料:

http://www.learncpp.com/cpp-tutorial/912-shallow-vs-deep-copying/

http://stackoverflow.com/questions/2657810/deep-copy-vs-shallow-copy

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值