1

To me, std::optional<T> always was a "cleaner" version of std::unique_ptr<T>: both have an empty state (optional() and nullptr) and own a T object otherwise. This analogy, however, breaks down when considering std::optional<const T>. The first code block is valid, while the second one should not be, as the type (const T) needs to be MoveAssignable.

std::unique_ptr<const int> ptr1, ptr2; ptr1 = std::move(ptr2); std::optional<const int> opt1, opt2; opt1 = std::move(opt2); 

With a similar reasoning, I would expect std::optional<T&> to be equivalent to a non-owning pointer T*. While this analogy is a bit blurry for general T, I think it would make much sense for const T.

const int ZERO = 0; void AssignPtrIfNull(const int*& ptr) { ptr = (ptr == nullptr ? &ZERO : ptr); } void AssignOptIfNull(std::optional<const int&>& ptr) { ptr = (ptr ? make_optional<const int&>(ZERO) : ptr); } 

So I am wondering, what is the thought process behind making optional the way it is? Because it seems really odd to me. Are there some pitfalls I am overseeing?

15
  • 1
    Why are you comparing std::optional with std::unique_ptr as they are different beasts? Commented Jan 1, 2017 at 12:37
  • Rationale can be found by reading about std::optional's ancestor boost::optional. They are quite close in spirit, despite the standard type having some small changes. Commented Jan 1, 2017 at 12:38
  • @EdHeal I thought I made my comparison clear; what part do you not understand? Of course they are different but optional always felt to me like a modern version of the "pass null as empty object" paradigm. Commented Jan 1, 2017 at 13:08
  • @StoryTeller Thanks, I will have a look to see if that clarifies the issue for me. Commented Jan 1, 2017 at 13:08
  • One is to do with pointers - the other is not Commented Jan 1, 2017 at 13:12

1 Answer 1

1

Like everything in the c++ standard library post c++11, std::optional was lifted straight out of the boost library suite.

The motivation is laid out here

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.