#include <algorithm> // std::copy
#include <cstddef> // std::size_t
#include <stdio.h> class dumb_array
{
public:
// (default) constructor
dumb_array(std::size_t size = 0)
: mSize(size),
mArray(mSize ? new int[mSize]() : 0)
{
printf("construct %p\n", this);
} // copy-constructor
dumb_array(const dumb_array& other)
: mSize(other.mSize),
mArray(mSize ? new int[mSize] : 0)
{
// note that this is non-throwing, because of the data
// types being used; more attention to detail with regards
// to exceptions must be given in a more general case, however
printf("copy-constructor %p\n", this);
std::copy(other.mArray, other.mArray + mSize, mArray);
} friend void swap(dumb_array& first, dumb_array& second) // nothrow
{
// enable ADL (not necessary in our case, but good practice)
using std::swap;
// by swapping the members of two classes,
// the two classes are effectively swapped
swap(first.mSize, second.mSize);
swap(first.mArray, second.mArray);
} dumb_array& operator=(dumb_array other) // (1)
{
printf("other %p, operator= %p\n", &other, this);
swap(*this, other); // (2)
return *this;
} // destructor
~dumb_array()
{
printf("destruct %p\n", this);
delete [] mArray;
} private:
std::size_t mSize;
int* mArray;
}; int main()
{
dumb_array obj(100);
printf("test copy-constructor\n");
dumb_array copy_obj(obj); printf("test operator=\n");
dumb_array operator_obj;
operator_obj = obj; return 0;
} /*
construct 0x7fffdd3b4730
test copy-constructor
copy-constructor 0x7fffdd3b4720
test operator=
construct 0x7fffdd3b4710
copy-constructor 0x7fffdd3b4740
other 0x7fffdd3b4740, operator= 0x7fffdd3b4710
destruct 0x7fffdd3b4740
destruct 0x7fffdd3b4710
destruct 0x7fffdd3b4720
destruct 0x7fffdd3b4730
*/

参考资料

What is the copy-and-swap idiom?

More C++ Idioms/Copy-and-swap

最新文章

  1. Ubuntu安装sougou输入法
  2. java通过反射获取调用变量以及方法
  3. RESTFul API 一些文章
  4. Oracle创建表空间、创建用户、授权用户、导入dmp备份语句
  5. ysql+heartbeat+DRBD+LVS实现mysql高可用
  6. 字符串-06. IP地址转换
  7. [LeetCode] Longest Substring Without Repeating Characters (LinkedHashSet的妙用)
  8. 为vue添加公用方法,vue添加通用方法
  9. REST(Representational state transfer)的四个级别以及HATEOAS介绍
  10. 关于导入zepto出错的问题
  11. PAT甲 1032. Sharing (25) 2016-09-09 23:13 27人阅读 评论(0) 收藏
  12. React 的几个需要注意的地方
  13. QT下载地址大全
  14. [arc082E]ConvexScore-[凸包]
  15. VS2008链接错误fatal error LNK1104: cannot open file &#39;*.obj&#39;
  16. win下自动sftp脚本定时下载文件
  17. Java线程工作内存与主内存变量交换过程及volatile关键字理解
  18. 利用firebug 查看JS方法, JS 调试
  19. 从配置maven环境到maven项目的新建
  20. Android开发实践:掌握Camera的预览方向和拍照方向

热门文章

  1. apply和call
  2. 诺基亚XL中Intent.ACTION_VIEW无效的问题
  3. C语言解决八皇后问题
  4. 设置Android studio内容的主题
  5. Altium Designer 画"差分线"
  6. jdbc 配置
  7. c++构造函数的作用---13
  8. day17算法
  9. Nginx-uri、request_uri、document_uri之间的区别
  10. Cacti-安装和使用详解