https://www.learncpp.com/cpp-tutorial/the-hidden-this-pointer/
member function이 불리면 클래스 오브젝트에 내장되어 있는 this라는 포인터를 이용해
어떤 객체가 호출했는지 파악할 수 있다
simple.setID(2);
위의 코드를 보면 오직 argument만을 가지고 있는 것 처럼 보인다
하지만 컴파일 하면 컴파일러가 다음과 같이 바꿔준다
setID(&simple, 2); // note that simple has been changed from an object prefix to a function argument!
위와 같이 convert되어서 어떠한 객체가 함수를 호출했는지 argument로 전달한다
하지만 우리는 member function을 정의할 때 위와 같은 형태로 선언하지 않았다
void setID(int id) { m_id = id; }
위의 형태 또한 컴파일러가 다음과 같이 바꿔준다
void setID(Simple* const this, int id) { this->m_id = id; }
위의 코드에서 this라는 포인터를 볼 수가 있다
this 포인터는 항상 operated 되고 있는 object 자신을 가르키고 있는 포인터다
다음의 예시를 보자
int main()
{
Simple A{1}; // this = &A inside the Simple constructor
Simple B{2}; // this = &B inside the Simple constructor
A.setID(3); // this = &A inside member function setID
B.setID(4); // this = &B inside member function setID
return 0;
}
위 그림에서 this는 각 operate 하고 있는 객체 A, B의 주소를 가지고 있다