Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What strange magic is *this?

Tags:

c++

Quick question. I want to understand the behaviour of *this in C++. Forgive me if this is too obvious, or is a repeat, due to search engines interpreting * as a wildcard character my searches have been somewhat less than enlightening.

I'm using someone else's code, which has a number of functions that look like so:

(Type of N is struct)

N N::someMethod() const {

    N n = *this;
    // do a function that modifies internal values of the struct
    n.modify();
    return n;

}

What happens is that it returns a modified copy of the original struct, and the original struct is unmodified.

I assume that somehow *this is making a copy, but I don't understand why/how. Is this some magic to do with structs? Is it the const in the function declaration? Is there some other magic going on behind the scenes?

My understanding is that 'this' is a pointer. I had thought that when you * a pointer, it simply dereferenced that pointer?? (So I expected n to point to the same chunk of memory as the original, but obviously it doesn't, so my intuition is borken)

Please feel free to point out the error of my ways, in detail if you like. It's okay, I'm smart enough to grok a detailed technical discussion of what is going on under the hood, I promise!

like image 748
Rick Avatar asked Oct 25 '12 06:10

Rick


2 Answers

No, this is magic from before the dawn of time (a thinly veiled Narnia reference). It harkens back to the C language.

Since this is simply a pointer to the current object, *this is the object itself, and the line:

N n = *this;

simply makes a copy of said object. Then, it modifies that copy and returns it.

If you wanted a copy of the pointer to the same object, that would be:

N *n = this;

It's no different to the following:

int xyzzy = 7;           // xyzzy holds 7.
int *pXyzzy = &xyzzy;    // the address of xyzzy.

int plugh = *pXyzzy;     // a *different* address, also holding 7.
int *pTwisty = pXyzzy;   // copy *address*, pXyzzy/pTwisty both point to xyzzy.
like image 64
paxdiablo Avatar answered Sep 19 '22 18:09

paxdiablo


*this by itself does not make any copy, it just make type correct for copy constructor that will be called by N n = ....

like image 41
Alexei Levenkov Avatar answered Sep 22 '22 18:09

Alexei Levenkov