Should a C++ logger write method be defined as const?

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 const semantics: Developers often assume const methods cannot modify anything, but they can modify mutable fields.
  • 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 mutable if the method is const.

Real-World Impact

  • Incorrect const usage: Leads to compiler errors or unintended behavior if state is modified.
  • Performance implications: Unnecessary mutable fields 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 const if they don’t modify state.
  • Use mutable sparingly: Only for fields that logically need modification in const methods.
  • Document intent: Clearly state whether logging modifies internal state.

Why Juniors Miss It

  • Overlooking mutable: Juniors often forget mutable exists or misuse it.
  • Confusing side effects: Mistaking external I/O for internal state modification.
  • Fear of non-const methods: Assuming all methods should be const for safety.

Leave a Comment