简体   繁体   中英

C++: Create a new object with a reference variable

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?

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.

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) {}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM