Stroustrup 谈 C++ 11的新特性

转载自http://www.stroustrup.com/C++11FAQ.html

仅供个人参考, 收藏用

control of defaults: move and copy

By default, a class has 5 operations:
  • copy assignment
  • copy constructor
  • move assignment
  • move constructor
  • destructor
If you declare any of those you must consider all and explicitly define or default the ones you want. Think of copying, moving, and destruction as closely related operations, rather than individual operations that you can freely mix and match - you can specify arbitrary combinations, but only a few combinations make sense semantically.

If any move, copy, or destructor is explicitly specified (declared, defined, =default, or =delete) by the user, no move is generated by default. If any move, copy, or destructor is explicitly specified (declared, defined, =default, or =delete) by the user, any undeclared copy operations are generated by default, but this is deprecated, so don't rely on that. For example:

 	class X1 { 		X1& operator=(const X1&) = delete;	// Disallow copying 	}; 
This implicitly also disallows moving of X1s. Copy initialization is allowed, but deprecated.
 	class X2 { 		X2& operator=(const X2&) = delete; 	}; 
This implicitly also disallows moving of X2s. Copy initialization is allowed, but deprecated.
 	class X3 { 		X3& operator=(X3&&) = delete;	// Disallow moving 	}; 
This implicitly also disallows copying of X3s.
 	class X4 { 		~X4() = delete;	// Disallow destruction 	}; 
This implicitly also disallows moving of X4s. Copying is allowed, but deprecated.

I strongly recommend that if you declare one of these five function, you explicitly declare all. For example:

 	template<class T> 	class Handle { 		T* p; 	public: 		Handle(T* pp) : p{pp} {} 		~Handle() { delete p; }		// user-defined destructor: no implicit copy or move   		Handle(Handle&& h) :p{h.p} { h.p=nullptr; }			// transfer ownership 		Handle& operator=(Handle&& h) { delete p; p=h.p; h.p=nullptr; return *this; }	// transfer ownership  		Handle(const Handle&) = delete;		// no copy 		Handle& operator=(const Handle&) = delete;  		// ... 	}; 

See also

the C++ draft section ??? [N2326==07-0186] Lawrence Crowl:  Defaulted and Deleted Functions.[N3174=100164] B. Stroustrup:  To move or not to move. An analysis of problems related to generated copy and move operations. Approved.

 

转载于:https://www.cnblogs.com/likeatree/p/4193886.html

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值