C,C++/C++
[C++] 멤버 변수의 오프셋을 계산해주는 offsetof 매크로
woohyeon
2020. 2. 29. 14:27
반응형
#define offsetof(type, member)
[매개 변수]
type: 구조체 또는 클래스의 이름
member: 멤버 변수 이름
[반환값]
type 내의 member의 offset을 계산하여 반환한다.
C++ 17 미만은 type으로 오직 standard layout type 대해서만 그 기능이 정의되어있다. standard layout type이란 오직 C 스타일의 데이터로만 이루어진 데이터 구조 타입을 말한다. 예를 들면 기본 타입 int, float, double, char 등, 함수가 포함되지 않은 구조체가 그 예이다.
C++ 17부턴 함수가 포함된 클래스의 멤버 변수의 오프셋도 계산할 수 있다.
[예제]
class Foo
{
public:
Foo() = default;
~Foo() = default;
void Func1() const;
void Func2() const;
int mInteger;
float mFloatingPoint;
char mCharacter;
char mString[10];
char* mCharPtr;
string mStringClassType;
vector<string> mVector;
};
int main()
{
cout << offsetof(Foo, mInteger) << endl;
cout << offsetof(Foo, mFloatingPoint) << endl;
cout << offsetof(Foo, mCharacter) << endl;
cout << offsetof(Foo, mString) << endl;
cout << offsetof(Foo, mCharPtr) << endl;
cout << offsetof(Foo, mStringClassType) << endl;
cout << offsetof(Foo, mVector) << endl;
return 0;
}
[결과]