In C ++, Do objects are copied onto the stack when I pass their functions by value?

I am just starting to get into C ++ (I'm an experienced Python / Java developer, getting into the best parts of OpenCL), and I'm very confused about how objects are passed to functions.

Say I have a simple class:

class Thing { int var; int var2; int var3; void doSomething(); }; 

Now the "size" of this class is at least 3*sizeof(int) (I'm not sure if the function pointer is saved or not). Now let's say that I have two function signatures:

 void doThing1(Thing t); void doThing2(Thing* t); 

When I call doThing1 , does copying the whole instance doThing1 cause? When I call doThing2 , is only the stack space sizeof(Thing*) required?

Many "ordinary wisdom" on the Internet told me to try using the signature of the doThing1 function, but at first glance it seems very silly - if it really copies the entire object.

I also assume that if a function is going to modify an object that is on the heap (created with the new keyword), it should look like doThing1 .

Please correct my ignorance. Either my Google searches do not help, or Google does not help.

+4
source share
4 answers

When I call doThing1, does copying the whole instance onto the stack cause? When Ic is all doThing2, is only sizeof stack space (Thing *) required?

Yes and yes.

Many "common reasoning" on the Internet told me to try using the signature of the doThing1 function

Where?

If you need to change the Thing in the called, you will need to pass a pointer or a link. If you do not need to change Thing , you just need to pass the link to const (giving you protection against erroneous changes in the state of the pass by value, with the efficiency of passing through the link).

 void doThing(const Thing& t) 
+5
source

When I call doThing1, does copying the whole instance onto the stack cause? When I call doThing2, is only the stack space sizeof (Thing *) required?

Yes and yes.

Now the "size" of this class is at least 3 * sizeof (int) (I'm not sure if the function pointer is saved or not).

There is no function pointer; size 3 x SizeOf (INT). (demo)

+3
source

In both cases, you are right. You can also use a link that avoids copying, but also avoids pointers:

 void doThing2(const Thing& t); 

This would be my preference, as it is easily optimized by the compiler and helps to avoid errors (for example, re-assignment in a function).

+2
source

pass them with a constant void doThing1( const Thing &t)

+1
source

All Articles