Reputation: 24685
Consider this piece of code:
int *a, *b;
a = foo();
if (a)
b = a;
a = bar();
The problem is, when a
updates by calling bar()
, b
also updates. However I want to make a backup by using b = a
. What is the problem then?
Upvotes: 2
Views: 29549
Reputation: 52107
The...
int *a;
// ...
a = foo();
...would not even compile if the function was declared as int foo();
, so I'll assume it's declared as int* foo();
. Ditto for int* bar();
.
Don't return a raw pointer like this. It might not be clear whether caller should delete
it or not. The good documentation can only partially resolve this problem (human beings have a tendency of ignoring the documentation from time to time). Why not just copy the integer value, or at least return a reference to integer in case it really needs to be shared?
That being said, in your particular case, foo()
and bar()
apparently use the same int "object" internally, so a
continues to point to the same object as b
even after bar()
has modified it.
Upvotes: 0
Reputation: 4205
int *a, *b;
b = new int;
a = foo();
if (a)
*b = *a;
a = bar();
...
delete(b);
(The value at address a is assigned to the value at address b.)
What you are doing right now is making a and b point to the same place in memory. Then, if the value in a or b is updated, they pointers both point to the new value.
By the way, unless bar()
returns a pointer, you probably want *a = foo()
and *a = bar()
.
Upvotes: 2
Reputation: 11
if a == b, then bar() is changing the value at a, not assigning a new a. This makes the most sense memory wise. If what you care about is the actual integer, not the address, instead of assigning b = a assign *b = *a.
Upvotes: 0
Reputation: 14053
You could just back up the value of a:
int *a, b;
a = foo();
if (a)
b = *a;
a = bar();
or if you want to keep b
as a pointer:
...
*b = *a;
...
Upvotes: 1