Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding function parameters to a vector

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?

like image 598
user3809200 Avatar asked Dec 06 '22 12:12

user3809200


2 Answers

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.)

like image 68
juanchopanza Avatar answered Dec 26 '22 00:12

juanchopanza


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.

like image 22
bipll Avatar answered Dec 26 '22 00:12

bipll