So sometimes I want an object to have a reference to a shared resource (let’s say something of type A), or alternatively to have its own copy of an A.
Furthermore the object may find itself inserted and manipulated inside of containers (vector, list, set).
So far what I know is that I will want to use an implementation of unique_ptr if I have a polymorphic type that is to be in a container. So for a class HasAnA which owns an A to be able to be placed inside a container while still allowing its A‘s to also be B‘s (B in this case being a derived class of A), it must be like this:
class A {
virtual void a() { std::cout << "A" << endl; }
payloadA payload;
};
class B: public A {
void a() { std::cout << "A(B)" << endl; }
void b() { std::cout << "B" << endl; }
payloadB payload;
};
class HasAnA {
std::unique_ptr<A> my_A; // this allows me to build a std::vector<HasAnA>
OtherStuff my_other_stuff;
};
So this is great, what I’m looking for is how to implement a class I’ll call RefersAnA. I’d like for a RefersAnA to either have ownership of its own A, OR refer to an A owned by something else.
Let’s see.
class RefersAnA {
std::unique_ptr<A> my_A; // represents my own A: when I die, this A is dealloc'd
A* not_my_A; // someone else's A.
OtherStuff my_other_stuff;
RefersAnA () {
// in here is code that would skip initializing my_A if a valid A* was provided.
}
};
To me this isn’t really as friendly as I would like. Could I make some sort of template class which abstracts the notion of “either being a unique ptr to the resource or a raw ptr to the resource”? It needs one bit to say which of the two it is, and one pointer.
Here’s an idea:
(Instead of
own(new T)I would of course preferown(make_unique<T>()), but that’s a separate issue.)