h8n2
h8n2

Reputation: 679

Copying a pointer, change what the copy is pointing to without changing original?

Is it possible to copy a pointer, and then change the value it's pointing to without changing what the original pointer is pointing to?

For example, say I had the following:

int *i;
auto j = i;

*j = new_val;

This would change the value stored at the address i is pointing to because both i and j are pointing to the same memory address, which I do not want.

Since this example case is so simple, I could simply just create a new int *j without copying over i. But in more complicated cases, such as a linked list, I would not want to recreate a linked list.

So I guess my question boils down to if it is possible to copy a pointer, and have the copy point to a different address but maintain the structural integrity of the original pointer?

Upvotes: 2

Views: 4213

Answers (1)

Resurrection
Resurrection

Reputation: 4106

First some clarification. Pointer is a standalone variable that holds a memory address. Nothing more, nothing less. The type of the poitner means that you, the programmer, told the compiler what is stored at that address so that you can retrieve the value stored at that address - this is called dereferencing.

Now with that in mind you should be able to work out what you want to do yourself but let us walk through the process and we will use smart pointers because they help us manage the memory:

std::unique_ptr<int> i = std::make_unique<int>(10); 
//Here we created a variable on the heap and gave it a value 10,
//the address of it is stored in **i**

std::unique_ptr<int> j = std::make_unique<int>(*i);
//Here we created a variable on the heap nad gave it a value
//stored at the address in **i**. Notice the dereferencing
//that means we want to copy the value pointed to,
//not the pointer itself.

Now without smart pointers if that makes more sense for you:

int *i = new int(10);
int *j = new int(*i);
delete i;
delete j;

This does the same thing but you need to manage the memory yourself and it will leak when an exception is thrown for example.

Now this will work for all types that are either trivial like an int in the example or those that have the copy constructor defined. Compiler will typically generated one for your types automatically unless it cannot do that for some reason in which case you will have to provide it yourself:

See here for more details: Copy Constructors

EDIT: Some very good explanation of pointers including demonstration of how to do what you want to do: C++ Pointers by TheCherno

Upvotes: 4

Related Questions