Hey guys I am quite confused as to why this is happening
so I looked up the arguments for std::vector.push_back() and it accepts a const reference of any type,
but when I change the original type lets say I change a string to "blah" from "hey" shouldn't this change also happen in the vector,since vector is holding a reference to the string h and not a copy?
or does the const keyword change this? and how?
thanks
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
int main()
{
string h = "hey";
vector<string> vec;
vec.push_back(h);
h = "blah";
for(int i = 0; i < vec.size(); i++){
cout << vec[i] << endl;
}
}
but when I change the original type lets say I change a string to "blah" from "hey" shouldn't this change also happen in the vector,since vector is holding a reference to the string h and not a copy?
You pass in a const reference, and that is copied into the container.
A const reference is used because you can have a vector to any type. That type may be large, and a const reference is passed to avoid copying the object onto the stack.
If push_back didn't take a reference as argument the object would have to be copied twice. Once when the argument is passed to function and once again when the function copies the object to the internal array. The first copy is avoided when the argument is passed by reference.
val is passed by reference for the same reason that the argument to push_back was passed by reference, namely to avoid unnecessary copies.
destroy() destroys the object but doesn't deallocate the memory so you could still reuse the same memory to construct a new object using construct() if you wanted.