Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Take value out of C++ std::optional

How do you actually take a value out of optional? Meaning take ownership of the value inside the std::optional and replace it with std::nullopt (or swap it with another value)?

In Rust for example you could .unwrap your Option or do something like foo.take().unwrap(). I’m trying to do something like that with C++ optionals.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

operator*/value() returns a reference to the value held by the optional, so you can simply use std::move to move it to a temporary variable

std::optional<std::string> opt = "abc";
// "take" the contained value by calling operator* on a rvalue to optional
auto taken = *std::move(opt);

This will invoke the rvalue reference overload of operator*() of the optional, which returns an rvalue reference to the contained value.

You can also directly perform std::move on the return value of the operator*() of the lvalue optional, which will convert the lvalue reference of the contained value into an rvalue

auto taken = std::move(*opt);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading