0

Suppose I have two functions

void ProcessData(HugeDataStructure &data) { DoSomething(data); }
void ProcessDataInefficiently(HugeDataStructure data) { DoSomething(data); }

In my code, I have a pointer to the data

HugeDataStructure *p = &SomeValidDataStructure;

When I invoke the function

ProcessDataInefficiently(*p);

I believe I am making a huge copy (of the data structure) onto the stack. On the other hand, when I invoke the function

ProcessData(*p);

am I still making a copy of the data onto the stack? In other words, is "*p" inducing a copy? Compare this case to the following case

*p = AnotherValidDataStructure;

Here, I am copying the contents of AnotherValidDataStructure into SomeValidDataStructure, so a copy is, in fact, performed. Does this hold when passing a dereferenced pointer where a reference is required? I'm pretty sure it does not, but can't find documentation to the effect.

Please, let's not get into a "when you should use pointers and when you should use references" discussion. I did not write the methods that I need to invoke, so it's out of my hands. I want to ensure I'm not making huge copies onto the stack when I invoke

ProcessData(*p);

vs

ProcessDataInefficiently(*p);

Thanks

MadHacker
  • 11
  • 2
  • no you're not making copies. – Jean-François Fabre Jan 14 '18 at 21:40
  • this isn't C. C doesn't have references – Jean-François Fabre Jan 14 '18 at 21:41
  • There are enough correct answers already, but one addition: `ProcessDataInefficiently(*p)` does perform a copy, but that's not because you wrote `*p`. It's because the class type function parameter `data` needs to be initialized, which means creating a fresh object of that class type, in this case by using a copy constructor. On the other hand, `ProcessData(*p)` doesn't do that because initializing a reference does not (in most cases) involve creating any object. – aschepler Feb 01 '18 at 01:26

2 Answers2

0

No, ProcessData(*p) doesn't copy *p onto the stack or anywhere else. It's passed directly.

You can add logging to copy/more constructors/assignment operators and see yourself.

HolyBlackCat
  • 78,603
  • 9
  • 131
  • 207
0

The result of dereferencing a pointer is an lvalue. This lvalue binds to the lvalue reference parameter of the function. There is no copy, since copies are (materialized) prvalues, and no part of your function call necessitates an glvalue-to-prvalue conversion.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084