John Lock
John Lock

Reputation: 791

std::optional and polymorphism

I have read on Stack Overflow in many posts that when pointer is used (for argument or return value) and nullptr is allowed (making it optional), it is generally better to use std::optional instead.

However what if the pointer refers to polymorphic type? Is it best to use std::optional or a pointer?

Upvotes: 9

Views: 3023

Answers (4)

Cheers and hth. - Alf
Cheers and hth. - Alf

Reputation: 145249

I have read on stackoverflow in many posts, that when pointer is used(for argument or return value) and nullptr is allowed(making it optional), it is generally better to use std::optional instead.

Presumably you're referring to using std::optional to carry a value other than pointer or reference. In which case you're talking about an optional in-argument or an optional return value.


Using optional for optional in-argument has the disadvantage that the object is copied, or at least moved, which can be undesirable. Also, it precludes polymorphism.

The simplest way to do it, which also avoids unnecessary copying, and supports polymorphism, is to use a pointer to const:

void foo( Some_type const* p_object )

But then a caller will have to use the & operator on the actual argument.

To simplify calls you can provide overloads as syntactic sugaring:

void foo() { foo( nullptr ); }
void foo( Some_type const& object ) { foo( &object ); }

which supports calls like

foo();

and

foo( o );

Using optional for a return value has the advantage that exception throwing can be avoided when the calling code checks properly for value presence. But it appears to preclude ordinary RVO (return value optimization) for the wrapped object – weasel word “appears” because I can't see an airtight proof of this, but still I can't see how RVO could be done. So when the case of no return value is rare, and/or efficiency is very important, it might be better to just throw an exception. C++ only supports (raw) pointers and references for polymorphic return values, and there is no difference in this respect between using optional and throwing an exception to indicate no return value.

For a polymorphic optional return value you can use a smart pointer like std::unique_ptr or std::shared_ptr, that handles the ownership.

Upvotes: 1

Yakk - Adam Nevraumont
Yakk - Adam Nevraumont

Reputation: 275385

You can write a polymorphic pseudo-optional.

You'll want to implement small object optimization with a bounded object size/alignment (possibly parameters), and include a base class plus a set of additonal operations to erase down to (like copy or move). I have written a bounded polymorphic type without the pointer fallback that simply failed to compile if it lacked space for a similar reason, probably posted somewhere on SO.

Optional is not polymorphic, but regular and pseudo-regular value-types can be. Most of the arguments for optional over pointers/smart ptrs are actually arguments for using regular and pseudo-regular non-allocating types.

Upvotes: 2

user6366161
user6366161

Reputation: 37

The std::optional proposal explicitly says it's not polymorphic:

value_ptr requires that the pointed-to object is allocated in the free store. This means that the sizeof(value_ptr<T>) is fixed irrespective of T. value_ptr is 'polymorphic': object of type value_ptr<T> can point to an object of type DT, derived from T. The deep copy preserves the dynamic type. optional requires no free store allocation: its creation is more efficient; it is not "polymorphic".

Your options boil down to raw pointer or unique_ptr. Use the unique_ptr if you need a copy and a raw pointer otherwise.

Upvotes: 3

Nicol Bolas
Nicol Bolas

Reputation: 473322

optional doesn't work with polymorphic types. It's a value type, and polymorphic base classes don't work in an optional. Just as putting polymorphic base classes in vector or similar containers doesn't work.

Return a pointer. There's a reason why the advice is usually stated as "generally".

Upvotes: 8

Related Questions