cv (const-volatility) specifiers

From Cppreference

Jump to: navigation, search
  • const - defines that the type is constant.
  • volatile - defines that the type is volatile.
  • mutable - defines that a member of a class does not affect the externally visible state of the class. mutable members can be modified in constant classes, that is constness is essentially ignored for the particular member.

[edit] Explanation

Note: cv-qualifiers and cv-specifiers (list above) are not the same thing.
The cv-qualifiers are properties of a type whereas cv-specifiers are language feature to define cv-qualifiers

Cv-qualifiers define two basic properties of a type: constness and volatility. A cv-qualifer can be one of the following: 'const volatile', 'const', 'volatile' or 'none'. const defines that a type is constant, volatile defines that the type is volatile. Non-constant and non-volatile type has no additional restrictions, whereas constant and volatile imply the following:

  • constant - the object shall not be modified. Attempt to do so results in undefined behavior. On most compilers it is compile-time error.
  • volatile - the object can be modified by means not detectable by the compiler and thus some compiler optimizations must be disabled.

There is partial ordering of cv-qualifiers by the order of increasing restrictions. The type can be said more or less cv-qualified then:

  • unqualified < const
  • unqualified < volatile
  • unqualified < const volatile
  • const < const volatile
  • volatile < const volatile

Any cv-qualifiers are part of the type definition, hence types with different cv-qualifications are always different types. Therefore casting is needed to match types when assigning variables, calling functions, etc. Only casting to more cv-qualified type is done automatically as part of implicit conversions. In particular, the following conversions are allowed:

  • unqualified type can be converted to const
  • unqualified type can be converted to volatile
  • unqualified type can be converted to const volatile
  • const type can be converted to const volatile
  • volatile type can be converted to const volatile

To convert to a less cv-qualified type, const_cast must be used.

[edit] Keywords

const, volatile, mutable

[edit] Example