Paul Manta
Paul Manta

Reputation: 31597

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?

For 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;
}

Upvotes: 0

Views: 260

Answers (2)

iammilind
iammilind

Reputation: 70096

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.

Upvotes: 1

Erik
Erik

Reputation: 91320

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.

Upvotes: 2

Related Questions