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

  1. prefer deleted functions to private undefined ones
  1. any function may be deleted, including non-member functions and template instantiations
 
C++ noexcept Keyword enum vs enum class
Zack Yang
Zack Yang
Just a humble bounty hunter🥷
公告
type
status
date
slug
summary
tags
category
icon
password
Hey there, welcome to my blog 👋
-- 这个博客写些什么 --
定期技术分享🤖
不定期发疯文学🤡