C++ error: use of deleted function


问题

使用traits接收来自中间件的变量,调用拷贝构造函数时提示use of deleted function错误。

解释

仔细检查对应类中定义了移动构造函数,而没有显式定义拷贝构造函数。而问题就出在这:

If the class definition does not explicitly declare a copy constructor, one is declared implicitly. If the class definition declares a move constructor or move assignment operator, the implicitly declared copy constructor is defined as deleted; otherwise, it is defined as defaulted.

深究

声明移动构造函数证明你的类需要深拷贝,对于包含指针的类,编译器简单的浅拷贝可能导致反复释放或野指针问题。推广至Copy constructor 、Move constructor 、Copy assignment operator 、Move assignment operator 、Destructor 这五个函数,定义了任何一个都会导致编译器认为你在主动管理资源,原本默认生成的函数可能无法满足需求甚至是错误的故被转换为delete强制用户手动实现,也就是rule of five规则。
一图胜千言

参考

Copy constructors - cppreference.com
C++ class declarations


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM