Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Pointer Deep Copy

I am trying to make a deep copy of a pointer to an array of integer, and am having trouble deciding what code is unnecessarily verbose and what is needed.

The pointer I am trying to copy is just a simple integer array.

int* vertexArray = new int[G->size()];

It contains the numbers 0 to size()-1 as its values. My first though was to make a new int* where equal to vertex array,

int* shortestTour = vertexArray

but I believe that will make the shortestTour change every time I permute the vertexArray. Is the only way to make a deep copy of this with a loop like this

for(int i=0; i<G->size(); i++){
    shortestTour[i] = vertexArray[i];
}

and then to run that loop every time I find a tour/path shorter than the current shortest?

EDIT: This is for a simple, brute force implementation of the travelling salesman problem.

like image 815
Xerunix Avatar asked May 10 '15 17:05

Xerunix


1 Answers

As you may have guessed, a deep copy is not copying the pointer (after all, a pointer is just an address that points to some memory location), but copying the memory that is being pointed by the pointer.

So, if you have

int* vertexArray = new int[G->size()];

a deep copy is

int* deepCopy = new int[G->size()];
for(size_t i = 0; i < G->size(); ++i)
    deepCopy[i] = vertexArray[i]; // copy the allocated memory 

Of course, there are smarter and faster ways of copying the memory, like

std::memcpy(deepCopy, vertexArray, sizeof(int)*G->size()); // should be faster

A shallow copy is just copying the pointer, not the memory,

int* shallowCopy = vertexArray;

Any modifications you'll make will be reflected by both shallowCopy and vertexArray pointers, as both now point to the same memory chunk.

You should think whether you need a deep copy or not. If you just want to share data around, you probably don't. If the data must be "local", then probably you do.

like image 153
vsoftco Avatar answered Sep 17 '22 17:09

vsoftco