이번 섹션에선 pointer와 const를 조합한 활용법에 대해서 설명한다
int main()
{
const int x { 5 }; // x is now const
int* ptr { &x }; // compile error: cannot convert from const int* to int*
return 0;
}
위의 코드는 컴파일 에러를 발생한다
const int는 int* 타입으로 받을 수 없기 때문이다
const lvalue는 그럼 어떠헥 pointer bind를 할 수 있나?
int main()
{
const int x{ 5 };
const int* ptr { &x }; // okay: ptr is pointing to a "const int"
*ptr = 6; // not allowed: we can't change a const value
return 0;
}
위 코드와 같이 const int타입은 const int* 타입으로 받아줘야 한다
단 const int 포인터는 그 자체로는 포인터가 const라는 것을 의미하는 것이 아니다 따라서
포인터가 가르키고 있는 lvalue의 주소 말고 다른 주소로 바꿀 수 있다
int main()
{
const int x{ 5 };
const int* ptr { &x }; // ptr points to const int x
const int y{ 6 };
ptr = &y; // okay: ptr now points at const int y
return 0;
}
위의 코드에서 처럼 다른 포인터로 수정할 수 있다
그렇다면 pointer를 수정할 수 없도록 하는 문법은 어떻게 사용하나?
int main()
{
int x{ 5 };
int y{ 6 };
int* const ptr { &x }; // okay: the const pointer is initialized to the address of x
ptr = &y; // error: once initialized, a const pointer can not be changed.
return 0;
}
위의 코드를 보면 asterisk 다음에 const 키워드가 자리한다
이러한 경우 pointer가 다른 주소를 가르키도록 수정이 불가능 해진다
단, const pointer는 수정이 불가능하므로 definition과 동시에 initialization이 되어야 함
그럼 const lvalue를 가르키는 const pointer는 어떻게 사용하나?
int main()
{
int value { 5 };
const int* const ptr { &value }; // a const pointer to a const value
return 0;
}
위와 같이 const int 타입 설정하고 asterisk 다음에 const를 넣어줌으로써
const int를 타입을 가르킬 수 있는 const pointer를 선언했다
int const x {};
const int y {};
const int* ptr{};
int const* ptr2{};
int const*const ptr3{};
위에서 활용한 모든 const의 위치는 valid하다
결국 asterisk가 있으면 전후에 위치에 따라 의미가 다르고
int const == const int 모두 같은 타입이라는 것을 알 수 있다
추가로 int* const ptr {nullptr}; 도 가능하다
다만 nullptr을 가르키는 const pointer라 쓸모가 없다 (주소 수정도 불가능해서)