Search⌘ K
AI Features

Default Construction

Explore how to efficiently create default-constructed objects inside std::optional using std::in_place in C++17. Understand constructor and destructor behavior to avoid unnecessary copies or moves, and learn approaches for handling non-copyable or non-movable types like std::mutex with std::optional.

We'll cover the following...

Movable Types

If you have a class with a default constructor, like:

C++
class UserName {
public:
UserName() : mName("Default")
{
}
// ...
};

How would you create an optional that contains UserName{}?

You can write:

C++
std::optional<UserName> u0; // empty optional
std::optional<UserName> u1{}; // also empty
// optional with default constructed object:
std::optional<UserName> u2{UserName()};

That works but it creates an additional temporary object. If we traced each different constructor and ...