다음을 통해 공유


this 포인터

this 포인터는 class, struct 또는 union 형식의 비정적 멤버 함수 내에서만 액세스할 수 있는 포인터입니다. 멤버 함수가 호출되는 개체를 가리킵니다. 정적 멤버 함수에는 this 포인터가 없습니다.

구문

this
this->member-identifier

설명

개체의 this 포인터는 개체 자체의 일부가 아닙니다. 개체에 대한 sizeof 문의 결과에 포함되지 않습니다. 비정적 멤버 함수가 개체에 대해 호출되는 경우 컴파일러가 개체의 주소를 숨겨진 인수로 함수에 전달합니다. 예를 들어, 다음 함수 호출은

myDate.setMonth( 3 );

다음과 같이 해석할 수 있습니다.

setMonth( &myDate, 3 );

개체의 주소를 멤버 함수 안에서 this 포인터로 사용할 수 있습니다. 대부분의 this 포인터 사용은 암시적입니다. class의 멤버를 참조할 때는불필요하더라도 명시적 this를 사용하는 것이 적절합니다. 예시:

void Date::setMonth( int mn )
{
   month = mn;            // These three statements
   this->month = mn;      // are equivalent
   (*this).month = mn;
}

멤버 함수에서 현재 개체를 반환하기 위해 *this 식이 주로 사용됩니다.

return *this;

this 포인터를 사용하여 자신에 대한 참조를 막기도 합니다.

if (&Object != this) {
// do not execute in cases of self-reference

참고 항목

this 포인터는 수정할 수 없으므로 this 포인터에 대한 할당은 허용되지 않습니다. 이전의 C++ 구현에서는 this에 할당할 수 있었습니다.

경우에 따라 this 포인터가 직접 사용됩니다(예: 현재 개체의 주소가 필요한 자체 참조 데이터 구조를 조작하는 경우).

예시

// this_pointer.cpp
// compile with: /EHsc

#include <iostream>
#include <string.h>

using namespace std;

class Buf
{
public:
    Buf( char* szBuffer, size_t sizeOfBuffer );
    Buf& operator=( const Buf & );
    void Display() { cout << buffer << endl; }

private:
    char*   buffer;
    size_t  sizeOfBuffer;
};

Buf::Buf( char* szBuffer, size_t sizeOfBuffer )
{
    sizeOfBuffer++; // account for a NULL terminator

    buffer = new char[ sizeOfBuffer ];
    if (buffer)
    {
        strcpy_s( buffer, sizeOfBuffer, szBuffer );
        sizeOfBuffer = sizeOfBuffer;
    }
}

Buf& Buf::operator=( const Buf &otherbuf )
{
    if( &otherbuf != this )
    {
        if (buffer)
            delete [] buffer;

        sizeOfBuffer =  strlen( otherbuf.buffer ) + 1;
        buffer = new char[sizeOfBuffer];
        strcpy_s( buffer, sizeOfBuffer, otherbuf.buffer );
    }
    return *this;
}

int main()
{
    Buf myBuf( "my buffer", 10 );
    Buf yourBuf( "your buffer", 12 );

    // Display 'my buffer'
    myBuf.Display();

    // assignment operator
    myBuf = yourBuf;

    // Display 'your buffer'
    myBuf.Display();
}
my buffer
your buffer

this 포인터 형식

this 포인터의 형식은 함수 선언에 const 및/또는 volatile 키워드가 포함되어 있는지 여부에 따라 달라집니다. 다음 구문에서는 멤버 함수의 this 형식을 설명합니다.

멤버 함수의 선언자는 cv-qualifier-list를 결정합니다. const 또는 volatile(또는 둘 다)일 수 있습니다. class-type은 class의 이름입니다.

this 포인터를 다시 할당할 수 없습니다. 멤버 함수 선언에 사용되는 const 또는 volatile 한정자는 다음 표와 같이 해당 함수 범위에서 this 포인터가 가리키는 class 인스턴스에 적용됩니다.

멤버 함수 선언 myClass로 명명된 class에 대한 this 포인터의 형식
void Func() myClass *
void Func() const const myClass *
void Func() volatile volatile myClass *
void Func() const volatile const volatile myClass *

다음 표에서는 constvolatile에 대해 자세히 설명합니다.

this 한정자의 의미 체계

한정자 의미
const 멤버 데이터를 변경할 수 없습니다. const가 아닌 멤버 함수는 호출할 수 없습니다.
volatile 액세스할 때마다 메모리에서 멤버 데이터를 로드하고 특정 최적화를 비활성화합니다.

const 개체를 const가 아닌 멤버 함수로 전달할 때 발생하는 오류입니다.

마찬가지로 volatile 개체를 volatile이 아닌 멤버 함수로 전달할 때도 발생하는 오류입니다.

const로 선언된 멤버 함수는 멤버 데이터를 변경할 수 없습니다. const 함수에서 this 포인터는 const 개체에 대한 포인터입니다.

참고 항목

생성자 및 소멸자는 다음과 같이 const 또는 volatile로 선언할 수 없습니다. 그러나 const 또는 volatile 개체에 대해 호출할 수 있습니다.

참고 항목

키워드