Reinitialize object without invalidating pointers

I have:
1
2
3
4
MyClass* A = new MyClass(1);
MyClass* B = A;
/* doing things with A */
// Here I need to reinitialize A (eg. new MyClass(2)) and update B automatically 
Is this possible? Or how can this problem be solved?
Last edited on
Yes it is possible. You can pass another new address in 'A' without losing the data in 'B'. That is one of the advantages of pointers.
Why are you using pointers in the first place? Why do you need two pointers pointing to the same object in the same scope?

1
2
3
MyClass* A = new MyClass(1);
MyClass* B = A;
A = new MyClass(2);


You still have the original object (because B is pointing to it) and you now also have this new object (because A is pointing to it).

I was saying if it was possible by changing A to update B too. Sorry for the misleading.
if value of A is modified then value of B is updated since they point to same location.

if address of A is changed then address of B needs to be deleted and reassigned to new address of A.
addresses can't be automatically updated.

however you can use std::shared_ptr and invoke reset() on A which will reduce the work needed.

for example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <memory>
#include <iostream>
using namespace std;

class MyClass
{
public:
	MyClass(int x) : x(x) {}
	int x;
};

int main()
{
	auto A = make_shared<MyClass>(1);
	auto B = A;
	cout << B->x << endl; // prints 1

	A.reset(new MyClass(2)); // assign new address to A
	B = A; // delete old address and re-assign B to A

	cout << B->x << endl; // prints 2

	return 0;
}


Last edited on
If you want B to basically be just another name for A, which is what it sounds like, you're asking about references.

1
2
MyClass* A = new MyClass(1);
MyClass*& B = A;


Now, B is just another name for A. Anything that happens to A happens to B as well, because B is just another name for A.
Topic archived. No new replies allowed.