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