Reputation: 1121
In a function I get as an argument the reference to a vector:
void myFunc (vector< int>& myRef) {...}
Now in this function I need to backup (because myRef will become something else) the reference to that particular vector:
vector< int>& myBackup = myRef
Now I want myRef to become a reference to a NEW COPY of that vector. How do I do that?
Can I just say
vector< int> myRef = myBackup
?
Is the result myBackup = a reference to the original object and myRef = a reference to a copy of the original object?
Upvotes: 1
Views: 103
Reputation: 69
To solve this problem you need to make deep copy You can use memcpy but it is not a safe way; or such as
vector<int> newVector;
newVector.reserve(myRef.size()); //for performance, to avoid realloc
for (vector< int>::iterator it = myRef.begin();it!=myRef.end();++it)
newVector.push_back(*it);
myRef = newVector;
And after this line
vector< int>& myBackup = myRef
you have a compiler error with redeclaration of myRef...
Upvotes: 0
Reputation: 43
Does this code compile? You should really make use of a pointer here, if you want to reassign, as references can't be reassigned. A simple rule of thumb is if you want to be able to reassign the variable use a pointer, so long as it is advisable to do so in the current situation.
For example:
void myFunction(std::vector<int*> myPtr) {}
Upvotes: 0
Reputation: 9383
C++ references cannot be changed to refer to new objects after they are initially assigned. If you need that kind of behavior, you have to use a pointer.
Upvotes: 2