https://www.learncpp.com/cpp-tutorial/type-deduction-with-pointers-references-and-const/
앞서 auto를 활용한 type deduction을 살펴봤다
참고로 auto는 const가 drop된다
만약 const를 그대로 유지하고 싶다면
const auto를 사용해야 한다
const double foo()
{
return 5.6;
}
int main()
{
const double cd{ 7.8 };
auto x{ cd }; // double (const dropped)
auto y{ foo() }; // double (const dropped)
return 0;
}
const double foo()
{
return 5.6;
}
int main()
{
const double cd{ 7.8 };
const auto x{ cd }; // const double (const reapplied)
const auto y{ foo() }; // const double (const reapplied)
return 0;
}
만찬가지로 ampersand를 활용한 pass by ref에서
ref가 drop된다
따라서 ref를 활용하고 싶다면 auto&을 사용해야 한다
#include <string>
std::string& getRef(); // some function that returns a reference to const
int main()
{
auto ref1 { getRef() }; // std::string (reference dropped)
auto& ref2 { getRef() }; // std::string& (reference reapplied)
return 0;
}
const int x; // this const applies to x, so it is top-level
int* const ptr; // this const applies to ptr, so it is top-level
top-level const는 object 그 자체에 적용된다
반면에
const int& ref; // this const applies to the object being referenced, so it is low-level
const int* ptr; // this const applies to the object being pointed to, so it is low-level
low-level const는 being ref or pointed가 const라는 의미이다
참고로 ref는 low-level const 밖에 없다 왜냐하면 ref 자체가 한번 bind가 되면
다른 variable을 참조하도록 수정이 불가능하다 내재적으로 const의 의미가 있는 것처럼..
이 부분은 궁금하면 자료를 보자
간랸하게 &가 먼저 drop되고 그 다음 const라고 한다
pointer의 경우 drop이 되지 않는다
#include <string>
std::string* getPtr(); // some function that returns a pointer
int main()
{
auto ptr1{ getPtr() }; // std::string*
auto* ptr2{ getPtr() }; // std::string*
return 0;
}
만약 auto*을 썼는데 pointer 변수가 아니면 compile error가 발생한다
auto를 써도 마찬가지로 asterisk의 위치에 따른 const의 위치로
low-level const인지 , top-level const인지 나뉠 수 있다
#include <string>
std::string* getPtr(); // some function that returns a pointer
int main()
{
const auto ptr1{ getPtr() }; // std::string* const
auto const ptr2 { getPtr() }; // std::string* const
const auto* ptr3{ getPtr() }; // const std::string*
auto* const ptr4{ getPtr() }; // std::string* const
return 0;
}