首页 > 编程语言 > 详细

Stroustrup 谈 C++ 11的新特性

时间:2014-12-30 16:59:27      阅读:291      评论:0      收藏:0      [点我收藏+]

转载自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

 

Stroustrup 谈 C++ 11的新特性

原文:http://www.cnblogs.com/likeatree/p/4193886.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!