SW 지식/C 와 C++ 공부
[C++] mutable 변수
김달리 kimdali
2021. 9. 3. 14:44
mutable의 사전적 정의
mutable
형용사
1.변덕스러운
2.변하기 쉬운
3.가변성의
그렇다면, C++에서 나오는 mutable 키워드는 무엇일까?
mutable specifier
- mutable - permits modification of the class member declared mutable even if the containing object is declared const.
즉, 객체가 const로 선언된 경우에도 변경 가능하도록 허용한다는 것을 나타낼 때 사용!
예를 들어,
struct MyInfo
{
int a;
mutable int b;
};
void main()
{
const MyInfo value = {5,8};
value.a = 4; // 에러
value.b = 7;
}
이러한 경우 const 구조체 value의 멤버 변수 a를 수정하는 것은 불가능.
하지만, mutable 키워드가 붙은 b의 경우 수정이 가능!