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)?

Answers


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)


There's no difference. Even the standard says the two are equivalent, and if there's any compiler out there that doesn't generate the same binary for both versions, it's a bad one.


Need Your Help

accessing a USB camera without drivers using WPF and C#

c# .net wpf camera usb

Hi I am using a USB camera which has a button to capture images. I have embedded in my application the code to capture images via web camera which is working fine. I have attached another camera vi...

Set dynamic value on EpicEditor

javascript html editor epiceditor

I am using a EpicEditor. Below is the code through which I am initializing by epiceditor:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.