Search code examples
c++architecturenullheap-memorysmart-pointers

Is there a never-null unique owner of heap allocated objects?


Currently, I'm storing a collection of std::unique_ptrs to heap allocated objects of a polymorphic type:

struct Foo {
  virtual ~Foo() = default;
};
Collection<std::unique_ptr<Foo>> foos;

The basic interface I need is putting / taking owners of Foo to / from foos. The objects stored in foos are never supposed to be nullptr so I'd like to replace runtime assert(owner_taken) with compile-time checks. Moreover, I would like to be capable of using non-null owners in the context where a nullable one may be expected.

Probably, I need to store something like unique_ref but how would I extract one from foos? I don't want a copy, I want the stored object itself, so owner->clone() isn't a solution. Neither I can std::move(owner) because the state of a "unique reference" would be invalid afterwards.

Is there a clean design decision?


Solution

  • Is there a never-null unique owner of heap allocated objects?

    There is no such type in the standard library.

    It is possible to implement such type. Simply define a type with unique_ptr member and mark the default constructor deleted. You can mark constructor from std::nullptr_t deleted also so that construction from nullptr will be prevented at compile time.

    Whether you construct from an external pointer, or allocate in the constructor, there is no alternative for checking for null at runtime.