Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C++, Do objects get copied to the stack when I pass them to a function by value?

Tags:

c++

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

Let's 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 a function pointer is stored or not). Now say I have two function signatures:

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

When I call doThing1, does it cause the entire instance to be copied onto the stack? When I call doThing2, does it only require sizeof(Thing*) stack space?

A lot of "conventional wisdom" out there on the Internet has been telling me to try to use the function signature of doThing1, but at first glance that seems very silly -- if it does indeed copy the entire object.

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

Please, correct my ignorance. Either my Google searches aren't being helpful or Google isn't being helpful.

like image 551
Ryan Marcus Avatar asked Dec 21 '22 19:12

Ryan Marcus


1 Answers

When I call doThing1, does it cause the entire instance to be copied onto the stack? When Ic all doThing2, does it only require sizeof(Thing*) stack space?

Yes and yes.

A lot of "conventional wisdom" out there on the Internet has been telling me to try to use the function signature of doThing1

Where?

If you need to modify Thing in the callee, then you will have to pass a pointer or reference. If you don't need to modify Thing, you should just pass a const reference (giving you the protection from errant state modification of pass by value, with the efficiency of pass by reference).

void doThing(const Thing& t)
like image 139
Mud Avatar answered Jan 26 '23 00:01

Mud