These classes seem terrible, but assuming they are simply to demonstrate some real world code, you have a few options (which don't modify the classes).
As proposed in the comments by @Igor, you could simply give the classes two separate instances of A
. This may or may not suit your needs however, as perhaps they are meant to work on the same instance but it wasn't made clear:
int main()
{
A* a1 = new A();
A* a2 = new A();
Test test;
Test2 test2;
test.a = a1;
test2.a = a2;
}
If you needed for them to operate on the same instance, you can simply set one to nullptr
before it destructs. It would probably make more sense to change them both, and manage the memory yourself though:
int main()
{
std::unique_ptr<A> a = std::make_unique<A>();
Test test;
Test2 test2;
test.a = a.get();
test2.a = a.get();
// Use Test etc:
...
test.a = nullptr;
test2.a = nullptr;
// a goes out of scope and cleans itself up
}
Further depending on your uses, you could make a TestWrapper
class. This works for the classes provided, but the two classes you provided might provide all sorts of different functionality, in which case you could consider making T public
:
template <typename T>
struct TestWrapper
{
TestWrapper(A* a) { t.a = a; }
~TestWrapper() { t.a = nullptr; }
private:
T t;
};
int main()
{
std::unique_ptr<A> a = std::make_unique<A>();
{
TestWrapper<Test> test(a.get());
TestWrapper<Test2> test2(a.get());
}
}