Click here to Skip to main content
15,900,389 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Is there a difference in cost between the initialization of A and B in the following code?

C++
int main() 
{
   Class* pClass = new Class;
   Class A = *pClass; //All heap object is dereferenced.
   auto B = (*pClass).member; //Is all heap object dereferenced or just the member?
}


The initialization of A will dereference the entire object pointed to by pClass, which means that all of its members will be copied from the heap to the stack. Does the same happen in the initialization of B? Or is the initialization of B less costly because only one member of the object will be dereferenced?

Another similar question:

C++
class Thing
{
public:
   Class1 member1;   
   Class2 member2;   
   Class3 member3;

   Class1 foo() 
   {
      return member1;
   }
};

int main() 
{
    Thing* pThing = new Thing;
    Thing A = *pThing; //All heap object is dereferenced.
    Class1 B = pThing->foo(); //Is the heap object entirely dereferenced?
}


In the above code, is the initialization of B less costly than the initialization of A? Since the function foo only deals with one member.

What I have tried:

Nothing....... Inapplicable.......
Posted
Updated 1-Feb-19 19:49pm
v2
Comments
Afzaal Ahmad Zeeshan 2-Feb-19 1:39am    
Why do that in the first place? You could consider using copy or move semantics if needed, and if you have to access the data for reading purposes, why not directly access via pointer?

Explain a bit, so that we may help you out.

1 solution

Quote:
The initialization of A will dereference the entire object pointed to by pClass, which means that all of its members will be copied from the heap to the stack. Does the same happen in the initialization of B? Or is the initialization of B less costly because only one member of the object will be dereferenced?

No it doesn't!
Dereferencing a pointer does not copy anything anywhere: and certainly not onto the stack! Think about it: the heap is several GB, each stack in probably around 1MB or less. You can't dereference a pointer ad copy the object onto the stack. All that happens when you dereference a pointer is that you "follow it" to the destination item.

Think of a pointer as the index in a book: you look up "CodeProject" in the index and it says "page 123, line 14, word 6". You open the book at page 123, count down lines to 14, then count words to 6 and there is the word "CodeProject". You haven't copied the book in whole or in part - you have just dereferenced the index pointer to get to the data item.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900