Coming from a Java background I am confused with how C++ allows passing objects by value. I have a conceptual doubt regarding when objects are passed by value:
void add_to_vector(vector<SomeClass>& v, SomeClass var) {
v.push_back(var);
}
Is this conceptually correct? Here is why I feel this is wrong: var
is being passed by value and the memory for the object will be allocated on the stack for the function call. It is then getting added to the vector. At the end of the function call, the stack will be cleared and hence the object being referenced by var
will also be cleared. So vector will now contain an object which no longer exists after the function call.
Am I missing something?
You are missing the powerful concept of value semantics. Just like var
is a local copy in the function, std::vector
is designed such that after v.push_back(var);
, v
holds a copy of var
. This means that the elements of v
can be used without having to worry where they came from (unless SomeClass
has members with referential semantics, or in some way or another touches shared state.)
Yes, you're missing C++ value semantics. In Java, vectors only hold object references, object values themselves reside on the heap and are collected when no longer used. In C++, vectors hold object values, so practically always the vector will hold its own private value independent of function's local. Even if you passed var by reference, vector would hold its own private copy. Regard them as deep copies.
You might want to push_back(std::move(var))
here BTW, when var is passed by value in your example, if you don't plan to use the value after push_back.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With