mutable
When you declare a member function as const, it means the function is not allowed to modify any member variables of the object (except those declared as mutable
).
mutable
can only be applied to non-static and non-const data members.- It is typically used for caches, reference counts, logging info, etc.
mutable
only affects const member functions or const objects; in non-const contexts, it behaves like a normal member.
noexcept
the noexcept
keyword is used to specify whether a function is guaranteed not to throw exceptions. It is part of the exception specification system, introduced more formally in C++11 and enhanced in C++17 and beyond. If the compiler knows a function won’t throw, it can generate more efficient code.
If a function marked noexcept
does throw, std::terminate()
is called.
Usage
void func1() noexcept;
// in conditional form
void func2() noexcept(noexcept(other_func()));
When a std::vector
grows and needs to reallocate its storage (e.g., push_back
or emplace_back
), it must move or copy its elements to the new memory. If the element type has a move constructor that is noexcept, the std::vector
will use it. If not, and only a copy constructor is available (it’s safer), the std::vector
will use the copy constructor instead.
Whether the default constructor generated by compiler is marked noexcept
depends on whether moving all the members is noexcept.