在哪里放置这个指针,并在为它分配内存时?

2 c++ memory-management this

为什么指向虚函数表的指针会影响类的大小,但是这个指针不会影响类的大小?放置this指针的位置以及为其分配内存的位置?

Dan*_*rey 5

它作为隐式参数传递,因此不存储在对象内部.当你写:

struct X
{
    void f( int i );
};

X x;
x.f( 42 );
Run Code Online (Sandbox Code Playgroud)

你可以这样想:

void f( X* const this, int i ); // of course this would be illegal as "this" is a keyword

f( &x, 42 );
Run Code Online (Sandbox Code Playgroud)

所以this-pointer来自调用方法的地方.