Item10: Prefer scoped enums to unscoped enums
As a general rule, declaring a name inside curly braces limits the visibility of that name to the scope defined by the braces.
- C++98-style enums: unscoped
- C++11 scoped enums
- enum classes
Scoped enums have a second compelling advantage: their enumerators are much more strongly typed.
- forward-declared
enum class color
To make efficient use of memory, compilers often want to choose the smallest underlying type for an enum that’s sufficient to represent its range of enumerator values.
- use of fwd-declared enum
The header containing these declarations requires no recompilation if enum’s definition is revised
Item 11: Prefer deleted functions to private undefined ones
- copy constructor
- copy assignment operator
The C++98 approach to preventing use of these functions is to declare them private and not define them
- “= delete”
- delete functions
Deleted functions may not be used in any way, so even code that’s in member and friend functions will fail to compile if it tries to copy objects.
Things to remember
- Prefer deleted functions to private udefined ones
- Any function may be deleted, including non-member functions and template instantiations
Item 12: Declare overriding functions override
The world of object-oriented programming in C++ revolves around classes, inheritance, and virtual functions.
Among the most fundamental ideas in this world is that virtual function implementations in derived classes override the implementations of their base class counterparts.
Member function reference qualifers are one of C++11’s less-public features
-
declare it override
-
two contextual keywords
override, final
Things to Remember
- Declare overriding functions override
- Member function reference qualifiers make it possible to treat lvalue and rvalue objects (*this) differently
本文探讨了C++中使用范围(scoped)枚举的优势,如增强类型安全,以及如何通过删除函数来防止不希望的拷贝行为。推荐在可能的情况下使用`enum class`代替传统的无范围(unscoped)枚举,并优先使用明确删除的函数而非私有未定义函数,以提高代码的清晰性和编译时检查。同时,指出声明覆盖函数时使用`override`关键字的重要性。
1368

被折叠的 条评论
为什么被折叠?



