Summary
Making the Logger::Write method const in C++ is debatable but depends on whether the method modifies object state. If it only writes to an external resource (e.g., terminal) without changing internal state, marking it const is correct. However, if it updates internal counters (e.g., message_count), it must use mutable for those fields or avoid const.
Root Cause
- Misunderstanding of
constsemantics: Developers often assumeconstmethods cannot modify anything, but they can modifymutablefields. - Overemphasis on immutability: Forgetting that logging is often a side effect, not state modification.
Why This Happens in Real Systems
- Logging as a side effect: Logging typically writes to external systems (files, terminals) without altering object state.
- Mutable fields: Internal counters or buffers may need updates, requiring
mutableif the method isconst.
Real-World Impact
- Incorrect
constusage: Leads to compiler errors or unintended behavior if state is modified. - Performance implications: Unnecessary
mutablefields can complicate thread safety.
Example or Code (if necessary and relevant)
class Logger {
public:
void Write(const std::string& msg) const {
std::cout << msg << std::endl; // No state change, valid as const
++message_count_; // Error unless message_count_ is mutable
}
private:
mutable int message_count_ = 0; // Allows modification in const methods
};
How Senior Engineers Fix It
- Separate concerns: Keep logging methods
constif they don’t modify state. - Use
mutablesparingly: Only for fields that logically need modification inconstmethods. - Document intent: Clearly state whether logging modifies internal state.
Why Juniors Miss It
- Overlooking
mutable: Juniors often forgetmutableexists or misuse it. - Confusing side effects: Mistaking external I/O for internal state modification.
- Fear of non-
constmethods: Assuming all methods should beconstfor safety.