C++ mutable: const 멤버 함수에서 캐시·카운터·mutex를 수정하는 경우와 남용 주의
이 글의 핵심
mutable은 비트 단위 const 대신 논리적 const를 지키기 위한 도구입니다. const 함수에서 캐시를 갱신하면 여러 스레드가 동시에 호출할 때 데이터 레이스가 생길 수 있어 mutable mutex를 함께 두는 패턴이 필요하고, 캐시 무효화 시점을 놓치면 오래된 값을 돌려준다는 점도 짚습니다.
mutable이란?
mutable 키워드는 const 멤버 함수에서도 수정 가능한 멤버 변수를 선언할 때 사용합니다.
class Cache {
mutable int accessCount = 0;
public:
int getData() const {
accessCount++; // OK: mutable
return 42;
}
};
왜 필요한가?:
- 캐싱: const 함수에서 캐시 업데이트
- 통계 수집: 읽기 함수에서 카운터 증가
- 동기화: const 함수에서 뮤텍스 잠금
- 지연 초기화: const 함수에서 리소스 초기화
// ❌ mutable 없이: 에러
class Counter {
int count = 0;
public:
void increment() const {
count++; // 에러: const 함수에서 수정 불가
}
};
// ✅ mutable 사용: OK
class Counter {
mutable int count = 0;
public:
void increment() const {
count++; // OK: mutable
}
};
mutable의 동작 원리:
class Example {
int normal;
mutable int mutableVar;
public:
void constFunc() const {
// normal = 10; // 에러: const 함수
mutableVar = 10; // OK: mutable
}
};
// 내부 동작 (개념적)
// const 함수는 this 포인터가 const Example*
// mutable 멤버는 const 제약에서 제외됨
const 멤버 함수 안에서 this의 타입이 const Example*가 되면, this->normal로 접근하는 모든 멤버의 타입에 const가 붙습니다. mutable은 이 규칙에서 특정 멤버만 빼 달라고 컴파일러에 알리는 지정자입니다. 그래서 적용 대상에도 제약이 있습니다. static 멤버(객체에 속하지 않음), 참조 멤버, 그리고 자기 자신이 const로 선언된 멤버(mutable const int x;)에는 붙일 수 없어 컴파일 에러가 납니다. mutable은 const 객체에도 적용되므로, const Cache c; c.getData();처럼 const로 선언한 객체의 mutable 멤버를 바꾸는 것도 정의된 동작입니다. 반면 mutable이 아닌 멤버를 const_cast로 억지로 바꾸는 것은 원래 const 객체였다면 미정의 동작입니다.
논리적 const vs 물리적 const:
| 개념 | 설명 | 예시 |
|---|---|---|
| 물리적 const | 메모리 상태 변경 불가 | const int x = 10; |
| 논리적 const | 외부에서 보이는 상태 불변 | 캐싱, 통계 수집 |
class Cache {
mutable bool cached = false;
mutable double cachedValue = 0.0;
public:
// 논리적으로는 const (외부에서 보이는 상태 불변)
// 물리적으로는 non-const (캐시 업데이트)
double getValue() const {
if (!cached) {
cachedValue = expensiveComputation();
cached = true;
}
return cachedValue;
}
};
const 멤버 함수에서의 mutable
const 멤버 함수 안에서는 this가 const T*로 고정되므로, 일반 데이터 멤버는 읽기 전용처럼 취급됩니다. 그런데 관측 가능한 동작(observable behavior)은 그대로인데 구현만 바꾸고 싶은 경우가 있습니다. 대표적으로 캐시·계측·동기화 객체입니다. 이때 해당 멤버만 mutable로 표시해 “논리적 constness는 유지하며, 구현 세부만 갱신한다”고 컴파일러와 독자에게 알립니다.
- 바깥 계약:
const메서드는 “객체의 추상적 상태를 바꾸지 않는다”는 뜻에 가깝습니다. - 안쪽 구현: 캐시나 락은 그 계약을 깨지 않으면서도 비트는 바뀔 수 있습니다.
반대로 mutable로 “실제 의미 있는 데이터”까지 const 안에서 바꾸기 시작하면 const가 무의미해지므로 설계가 흐트러집니다.
캐싱 패턴 심화
읽기 연산이 반복될 때 같은 입력에 대해 같은 결과를 보장한다면, 내부에 지연 계산 + 무효화를 둘 수 있습니다.
- 키: 입력이 바뀌면 캐시 비트를 끈다 (
valid = false등). - 스레드: 읽기만
const로 노출하고 캐시를mutable로 두되, 다중 스레드면 캐시 필드 접근도 뮤텍스나 원자 변수로 보호해야 합니다.mutable은 스레드 안전을 보장하지 않습니다.
class Stats {
mutable std::mutex m_;
mutable bool cacheValid_{false};
mutable double cache_{};
double input_{};
public:
void setInput(double x) { input_ = x; cacheValid_ = false; }
double meanExpensive() const {
std::lock_guard<std::mutex> lk(m_);
if (!cacheValid_) {
cache_ = input_ * 2; // 실제로는 무거운 계산
cacheValid_ = true;
}
return cache_;
}
};
이 예제에는 쉽게 놓치는 레이스가 하나 있습니다. 읽기 쪽 meanExpensive()는 락을 잡지만 setInput()은 락 없이 input_과 cacheValid_를 씁니다. 한 스레드가 setInput을 호출하는 동안 다른 스레드가 meanExpensive를 부르면 락이 한쪽에만 있으므로 보호가 되지 않습니다. 락은 같은 데이터를 건드리는 모든 경로가 함께 잡아야 의미가 있으므로, setInput에도 std::lock_guard<std::mutex> lk(m_);를 넣어야 올바릅니다.
C++ 표준 라이브러리는 “const 멤버 함수는 여러 스레드에서 동시에 호출해도 안전하다”는 가정을 깔고 설계되어 있습니다. 예를 들어 여러 스레드가 같은 std::vector의 size()나 operator[] const를 동시에 호출하는 것은 레이스가 아닙니다. 사용자 타입이 const 함수 안에서 mutable 캐시를 락 없이 갱신하면, 이 타입을 const&로 여러 스레드에 넘긴 사용자는 안전하다고 믿다가 데이터 레이스를 만나게 됩니다. 그래서 mutable 캐시를 둔 순간, 그 const 함수를 스레드 안전하게 만들 책임도 함께 생긴다고 보는 것이 좋습니다.
뮤텍스와 mutable
std::mutex, std::shared_mutex 등은 잠그는 행위 자체가 객체 상태를 바꿉니다. 그런데 const 메서드에서도 “상태를 읽되, 동시 접근만 막고 싶다”는 요구는 흔합니다. 따라서 뮤텍스 멤버는 거의 항상 mutable입니다.
lock()/unlock()이const메서드에서 호출 가능해야 하므로, 뮤텍스가mutable이 아니면 설계가 꼬입니다.- 읽기/쓰기 잠금을 나눌 때는
std::shared_mutex+shared_lock/unique_lock패턴과 함께 사용됩니다.
class Registry {
mutable std::shared_mutex rw_;
std::map<std::string, int> data_;
public:
int get(const std::string& k) const {
std::shared_lock<std::shared_mutex> lk(rw_);
auto it = data_.find(k);
return it == data_.end() ? 0 : it->second;
}
void set(std::string k, int v) {
std::unique_lock<std::shared_mutex> lk(rw_);
data_[std::move(k)] = v;
}
};
뮤텍스를 멤버로 두면 따라오는 부작용도 알아 두어야 합니다. std::mutex는 복사도 이동도 할 수 없으므로, 뮤텍스 멤버를 가진 클래스는 컴파일러가 복사 생성자와 이동 생성자를 자동으로 만들지 못해 use of deleted function 에러가 납니다. std::vector<Registry>에 넣거나 값으로 반환하려다 이 에러를 처음 보는 경우가 많습니다. 복사가 필요하다면 복사 생성자를 직접 작성해 원본의 락을 잡은 상태에서 데이터만 복사하고 뮤텍스는 새로 만드는 식으로 구현해야 합니다.
언제 사용해야 하나
적합한 경우:
- 논리적 불변을 유지한 채, 프로파일링·캐시·지연 초기화만 필요할 때.
const인터페이스를 넓게 유지하고 싶을 때 (예:const객체에 대해서도size()가 캐시를 채움).- 동기화 프리미티브처럼 “계약과 무관한” 내부 도구를 둘 때.
다른 선택을 먼저 고려할 경우:
- 정말 상태 변경이면
mutable대신 non-const 메서드로 올리는 편이 명확합니다. - 스레드 공유가 복잡하면 std::atomic, 외부 동기화, 또는 값 의미론으로 경쟁을 없애는 설계가 나을 수 있습니다.
남용 주의
mutable로 “비즈니스 데이터”를constAPI 안에서 숨겨 바꾸기 → 호출자가const참조로 안전하다고 믿기 어렵습니다.- 동일한
const메서드가 여러 스레드에서 캐시를 갱신하는데 락이 없음 → 데이터 경쟁. - 과도한
mutable는 “이 객체는 사실상 항상 변한다”는 신호이므로, API를const가 아닌 메서드로 재구성하는 편이 낫습니다.
사용 이유
// const 함수에서 멤버 수정 필요
class Logger {
mutable std::mutex mtx;
public:
void log(const std::string& msg) const {
std::lock_guard<std::mutex> lock(mtx); // OK
// ...
}
};
실전 예시
예시 1: 캐싱
class ExpensiveCalculation {
mutable bool cached = false;
mutable double cachedValue = 0.0;
public:
double calculate() const {
if (!cached) {
// 복잡한 계산
cachedValue = /* ... */;
cached = true;
}
return cachedValue;
}
};
예시 2: 통계 수집
class DataProcessor {
mutable size_t readCount = 0;
mutable size_t writeCount = 0;
std::vector<int> data;
public:
int get(size_t index) const {
readCount++; // OK: mutable
return data[index];
}
void set(size_t index, int value) {
writeCount++;
data[index] = value;
}
size_t getReadCount() const {
return readCount;
}
};
예시 3: 지연 초기화
class Database {
mutable std::unique_ptr<Connection> conn;
public:
Connection* getConnection() const {
if (!conn) {
conn = std::make_unique<Connection>();
}
return conn.get();
}
};
지연 초기화 예제는 단일 스레드에서만 안전합니다. 두 스레드가 동시에 getConnection()을 호출하면 둘 다 !conn을 보고 연결을 두 번 만들고, 한쪽이 다른 쪽의 unique_ptr를 덮어써 먼저 반환된 포인터가 해제된 객체를 가리킬 수 있습니다. 여러 스레드에서 부를 수 있다면 mutable std::once_flag initFlag;를 두고 std::call_once(initFlag, [this] { conn = std::make_unique<Connection>(); });로 초기화를 한 번만 실행하게 하는 것이 표준적인 방법입니다. 또 const 함수가 non-const Connection*를 돌려주므로 호출자가 연결 상태를 바꿀 수 있다는 점도 설계상 의도인지 확인해야 합니다.
예시 4: 멀티스레딩
#include <mutex>
class ThreadSafeCounter {
mutable std::mutex mtx;
int count = 0;
public:
void increment() {
std::lock_guard<std::mutex> lock(mtx);
count++;
}
int get() const {
std::lock_guard<std::mutex> lock(mtx); // OK: mutable
return count;
}
};
자주 발생하는 문제
문제 1: 남용
// ❌ 논리적 const 위반
class BadClass {
mutable int value;
public:
void setValue(int v) const {
value = v; // const 의미 상실
}
};
// ✅ 올바른 사용
class GoodClass {
mutable int cacheHits;
public:
int getData() const {
cacheHits++; // 통계만 수정
return 42;
}
};
문제 2: 스레드 안전성
// ❌ 경쟁 조건
class Counter {
mutable int count = 0;
public:
void increment() const {
count++; // 스레드 안전하지 않음
}
};
// ✅ 뮤텍스 사용
class Counter {
mutable std::mutex mtx;
mutable int count = 0;
public:
void increment() const {
std::lock_guard<std::mutex> lock(mtx);
count++;
}
};
문제 3: 캐시 무효화
class Cache {
mutable bool valid = false;
mutable int cachedValue;
public:
void invalidate() {
valid = false; // 비const 함수
}
int getValue() const {
if (!valid) {
cachedValue = compute();
valid = true;
}
return cachedValue;
}
};
문제 4: const 포인터
class MyClass {
mutable int* ptr;
public:
void modify() const {
ptr = new int(10); // OK: 포인터 자체를 바꾸려면 mutable 필요 (이전 값은 누수)
*ptr = 20; // OK: 가리키는 값 수정은 mutable이 없어도 허용됨
}
};
이 예제는 const가 얕다(shallow)는 점을 보여 줍니다. const 멤버 함수 안에서 int* ptr은 int* const, 즉 “포인터 변수는 못 바꾸지만 가리키는 int는 바꿀 수 있는” 타입이 됩니다. 그래서 두 번째 줄 *ptr = 20은 mutable이 없어도 컴파일되고, mutable이 필요한 것은 첫 줄처럼 포인터 자체를 다시 대입할 때뿐입니다. std::unique_ptr<T> 멤버도 같아서 const 함수에서 ptr_->modify()가 통과됩니다. 이 구멍을 막고 싶다면 C++ 라이브러리 기초 TS의 propagate_const 같은 래퍼(구현에 따라 std::experimental::propagate_const)를 쓰거나, 가리키는 대상에 대한 const 접근자만 노출하는 식으로 설계해야 합니다.
사용 가이드라인
// ✅ 적절한 사용
// 1. 캐싱
mutable bool cached;
mutable double cachedValue;
// 2. 통계/로깅
mutable size_t accessCount;
// 3. 동기화
mutable std::mutex mtx;
// 4. 지연 초기화
mutable std::unique_ptr<Resource> resource;
// ❌ 부적절한 사용
// 논리적 const 위반
mutable int importantData;
실무 패턴
패턴 1: 지연 계산 캐시
class Matrix {
std::vector<std::vector<double>> data_;
mutable bool determinantCached_ = false;
mutable double cachedDeterminant_ = 0.0;
public:
Matrix(std::vector<std::vector<double>> data) : data_(std::move(data)) {}
double determinant() const {
if (!determinantCached_) {
cachedDeterminant_ = computeDeterminant();
determinantCached_ = true;
}
return cachedDeterminant_;
}
void modify(size_t i, size_t j, double value) {
data_[i][j] = value;
determinantCached_ = false; // 캐시 무효화
}
private:
double computeDeterminant() const {
// 복잡한 계산
return 1.0;
}
};
패턴 2: 스레드 안전 접근
#include <mutex>
#include <shared_mutex>
class ThreadSafeData {
mutable std::shared_mutex mtx_;
std::map<std::string, int> data_;
public:
int get(const std::string& key) const {
std::shared_lock lock(mtx_); // 읽기 잠금
auto it = data_.find(key);
return it != data_.end() ? it->second : 0;
}
void set(const std::string& key, int value) {
std::unique_lock lock(mtx_); // 쓰기 잠금
data_[key] = value;
}
};
패턴 3: 디버깅 정보
class Logger {
mutable size_t logCount_ = 0;
mutable std::chrono::steady_clock::time_point lastLog_;
public:
void log(const std::string& message) const {
logCount_++;
lastLog_ = std::chrono::steady_clock::now();
std::cout << "[" << logCount_ << "] " << message << '\n';
}
size_t getLogCount() const {
return logCount_;
}
};
FAQ
Q1: mutable은 언제 사용하나요?
A:
- 캐싱: const 함수에서 캐시 업데이트
- 통계 수집: 읽기 함수에서 카운터 증가
- 뮤텍스: const 함수에서 동기화
- 지연 초기화: const 함수에서 리소스 초기화
class Cache {
mutable bool cached_ = false;
mutable double cachedValue_ = 0.0;
public:
double getValue() const {
if (!cached_) {
cachedValue_ = compute();
cached_ = true;
}
return cachedValue_;
}
};
Q2: const 위반이 아닌가요?
A: 논리적 const는 유지됩니다. 외부에서 보이는 상태는 변하지 않으며, 구현 세부사항만 수정합니다.
// 논리적 const: 외부에서 보이는 상태 불변
class Cache {
mutable int accessCount = 0; // 통계 (내부 상태)
public:
int getData() const {
accessCount++; // 외부에 영향 없음
return 42;
}
};
Q3: 스레드 안전한가요?
A: mutable 자체는 스레드 안전하지 않습니다. 뮤텍스를 함께 사용해야 합니다.
class ThreadSafe {
mutable std::mutex mtx_;
mutable int count_ = 0;
public:
void increment() const {
std::lock_guard lock(mtx_);
count_++; // 스레드 안전
}
};
Q4: 성능 영향은?
A: 키워드 자체는 런타임 비용이 없습니다. 다만 mutable 멤버가 있는 const 객체는 읽기 전용 메모리(.rodata)에 배치될 수 없고, mutable 캐시를 보호하려고 뮤텍스를 두면 그 락 비용이 const 읽기 경로에 추가됩니다.
// mutable 유무는 성능에 영향 없음
int count_; // 일반 멤버
mutable int count_; // mutable 멤버
Q5: 남용 위험은?
A: const의 의미가 상실될 수 있습니다. 신중히 사용해야 합니다.
// ❌ 남용: 논리적 const 위반
class Bad {
mutable int value_;
public:
void setValue(int v) const {
value_ = v; // const 의미 상실
}
};
// ✅ 적절한 사용: 통계만 수정
class Good {
mutable int accessCount_;
int value_;
public:
int getValue() const {
accessCount_++; // 통계만 수정
return value_;
}
};
Q6: 람다에서도 사용할 수 있나요?
A: 가능합니다. 람다의 operator()를 non-const로 만듭니다.
int x = 0;
auto lambda = [x]() mutable {
x++; // OK: mutable
return x;
};
lambda(); // 1
lambda(); // 2
람다의 mutable은 멤버 변수의 mutable과 이름만 같을 뿐 동작 위치가 다릅니다. 값 캡처한 변수는 람다 객체(클로저)의 멤버가 되고, 람다의 operator()는 기본이 const라서 그 멤버를 수정할 수 없습니다. mutable을 붙이면 operator()가 non-const가 되어 클로저 안의 복사본을 바꿀 수 있게 됩니다. 바깥의 x는 여전히 0입니다. 또 람다를 복사하면 상태도 복사되므로, std::function에 넣거나 알고리즘에 값으로 넘긴 뒤에는 원래 람다와 상태가 따로 놉니다. 상태를 공유해야 한다면 참조 캡처나 shared_ptr를 써야 합니다.
Q7: mutable과 const_cast의 차이는?
A:
- mutable: 멤버 선언에 “const 문맥에서도 수정 가능”을 명시. const 객체에서도 정의된 동작
- const_cast: 표현식의 const를 벗겨 내는 캐스트(이것도 컴파일 타임에 처리됨). 원래 const로 선언된 객체를 이렇게 수정하면 미정의 동작
class Example {
mutable int x_;
public:
void func() const {
x_ = 10; // OK: mutable
// const_cast (위험)
const_cast<Example*>(this)->x_ = 10;
}
};
Q8: mutable 학습 리소스는?
A:
- “Effective C++” by Scott Meyers (Item 3)
- “C++ Concurrency in Action” by Anthony Williams
- cppreference.com - mutable
관련 글: const, mutex, lambda.
mutable은 const 멤버 함수에서도 수정 가능한 멤버 변수를 선언하는 키워드입니다.
같이 보면 좋은 글
- C++ const 정확성
- C++ static 멤버 변수와 함수: 초기화 순서, 스레드 안전성, C++17 inline static
- C++ this 포인터: 메서드 체이닝, 자기 대입 검사, 람다 this 캡처 수명
- C++ const 에러
- C++ 정적 초기화 순서
- C++ 람다 표현식 | 캡처·mutable·제네릭 람다와 재귀 람다