type
status
date
slug
summary
tags
category
icon
password
Delete special Member Functions
By default, C++ compilers provide certain special member functions for classes, including copy constructors, copy assignment operators, and more.
In C++98, if you want to prevent the use of these special member functions, the only way to do so is to declare them as private and not provide their definitions. The reason for not providing the function definitions is that in certain situations where there is still permission to access these special member functions (inside another member function or within a friend class), attempting to call these functions will result in a linker error because the linker couldn’t find the function definitions.
In C++11 and later, you can use the
delete
keyword to achieve the same (or even better) effect. We should always declare deleted functions as public members to ensure that the compiler provides the correct error messages (compiler checks for accessibility before deleted status).Another advantage of using
delete
is that it can be applied to non-member functions, typically to prevent undesirable implicit conversions. This is particularly useful when you want to avoid implicit type conversions between basic types.Additionally,
delete
can be used to prohibit the generation of unwanted template instantiations. In the case of pointer types, special handling is sometimes needed for void*
and char*
, which have unique behaviors:void*
cannot be dereferenced, and you cannot perform increment or decrement operations on it.
char*
typically points to a C-style string rather than a single character.
takeaways
- prefer deleted functions to private undefined ones
- any function may be deleted, including non-member functions and template instantiations
- 作者:Zack Yang
- 链接:https://zackyang.blog/article/cpp-deleted-functions
- 声明:本文采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处。
相关文章