开发者

C++ internals: Messing with the this-pointer

I have some questions about the internal workings of C++. I know for example that every member function of a class has an implied hidden parameter, which is the this-pointer (much in the same way Python does):

class Foo 
{
    Foo(const Foo& other);
};

// ... is actually...

class Foo
{
    Foo(Foo* this, const Foo& other);
};

Is it wrong of me to then assume then that the validity of the function does not directly depend on the validity of this (since it's just another parameter)? I mean, sure, if you try to access a member of the this-pointer, it better be valid, but the function will otherwise continue if this is deleted, right?

Fo开发者_如何学JAVAr example, what if I were to mess up with the this pointer and do something like what you see below? Is this undefined behavior, or is it defined by highly discouraged? (I'm asking out of pure curiosity.)

Foo:Foo(const Foo& other)
{
    delete this;
    this = &other;
}


You cannot assign to this - it is of type Foo * const. You can delete this; in certain circumstances, but it's rarely a good idea.


this is defined as,

Foo(Foo* const this, ...);

Casting away the constness is not not possible for this (special case). Compiler will give errors for the same. I have asked the similar question.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜