Search code examples
c++performancedereference

Is (*i).member less efficient than i->member


Having

struct Person {
   string name;
};

Person* p = ...

Assume that no operators are overloaded.


Which is more efficient (if any) ?

(*p).name vs. p->name

Somewhere in the back of my head I hear some bells ringing, that the * dereference operator may create a temporary copy of an object; is this true?


The background of this question are cases like this:

Person& Person::someFunction(){
    ...
    return *this;
}

and I began to wonder, if changing the result to Person* and the last line to simply return this would make any difference (in performance)?


Solution

  • When you return a reference, that's exactly the same as passing back a pointer, pointer semantics excluded.
    You pass back a sizeof(void*) element, not a sizeof(yourClass).

    So when you do that:

    Person& Person::someFunction(){
        ...
        return *this;
    }
    

    You return a reference, and that reference has the same intrinsic size than a pointer, so there's no runtime difference.

    Same goes for your use of (*i).name, but in that case you create an l-value, which has then the same semantics as a reference (see also here)