c++ const functions and mutable

 A const function prevents its value from being changed, but the value can be changed by using the mutable keyword.

Why is mutable necessary for a function that intentionally prevents its value from changing?

 

A const for a variable passed as a function parameter prevents the value itself from being changed, enabling safe use.

To ensure that a function does not change the value of a member variable, the const keyword is applied to the function declaration.

The const function raises several exceptions.

 

1. Cannot call functions other than the same const function.



2. Member variable values cannot be changed. (Global variables can be changed)

    In most cases, this is the desired situation.


If const is set on a class member function under development, it can be modified accordingly when there is an issue.

If setting it as const is difficult, you can solve it by deleting it.

 

The problem arises when you use an unmodifiable library and you need to override a const function.



If class Aa is a library class, Ba must define a const function.

If you need to change member variable values in Ba class, you cannot delete const or call a function without const.

At this time, if mutable is designated for the member number, the value of the member variable can be changed.


In general, const is used when you do not want to change the value of a member variable, so using mutable is awkward.

What if the printTest function runs in a multi-threaded environment and needs to be synchronized with a mutex?

void std::mutex::lock(); The function is not a const function, so you cannot use it in printTest.



"mutable std::mutex mMutex;" Similarly, if mutable is used, locking is possible even in const functions.

mutable is seen as a necessary feature for situations like this where it is logically necessary but can't use by const.

No comments:

Values used by crontab

cron is a command provided in Linux to periodically schedule specific tasks. Set up tasks through contab. editor settings When executin...