首页 > 代码库 > Stroustrup 谈 C++ 11的新特性
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 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.
Stroustrup 谈 C++ 11的新特性
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。