Saucy Dumpling
Saucy Dumpling

Reputation: 148

When does dereferencing a pointer cause a copy to be made in c++?

Basically I am curious when dereferencing a pointer causes a copy to be made. It is my understanding that pointers are a high level construct, and that if you dereference into a reference variable, it does not make a copy, but if you dereference into a variable, it does make a copy.

So this would not make a copy:

int num = 10;
int *ptr = #
int& num2 = *ptr;

But this would:

int num = 10;
int *ptr = #
int num2 = *ptr;

Is that correct? When exactly does referencing cause a copy to be made if ever?

Upvotes: 2

Views: 2589

Answers (1)

463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 122820

Dereferencing alone never makes a copy. Though dereferencing a pointer is just applying the * operator and there is more happening in your code.

Here:

int num = 10;
int *ptr = #
int& num2 = *ptr;

the last line dereferences the pointer and uses the result to initialize the reference num2. num2 now references num. No copies.

Here:

int num = 10;
int *ptr = #
int num2 = *ptr;

in the last line you first derference ptr then use the result to initialize num2. As num2 is a value a copy is made.

You do not need pointers to see the same effect:

int x = 42;
int& y = x;   // no copy, y is an alias for x
int z = x;    // z is a copy of x

Upvotes: 5

Related Questions