C++ optional::emplace() Function



The std::optional::emplace() function in C++, allows you to directly construct or reconstruct the value stored in the optional object, bypassing the need for a temporary value.

It initializes the contained value in place using the provided arguments, avoiding the unnecessary copies or moves. If the optional already contains the value, it is destroyed and a new value is created.

Syntax

Following is the syntax for std::optional::emplace() function.

T& emplace( Args&&... args );
or
T& emplace( std::initializer_list<U> ilist, Args&&... args );

Parameters

  • args − It indicates the arguments to pass to the constructor.
  • ilist − It indicates the initializer list to pass to the constructor.

Return Value

This function returns the reference to the new contained value.

Example 1

Let's look at the following example, where we are going to initialize a optional integer.

#include <iostream>
#include <optional>
int main() {
   std::optional < int > x;
   x.emplace(1121);
   if (x) {
      std::cout << "Result : " << * x << std::endl;
   } else {
      std::cout << "It is empty." << std::endl;
   }
   return 0;
}

Output

Output of the above code is as follows −

Result : 1121

Example 2

Consider the following example, where we are going initialize the optional with 'Welcome', then applying the emplace() to the replace the existing value.

#include <iostream>
#include <optional>
int main() {
   std::optional < std::string > x("Welcome");
   std::cout << "Before emplace: " << * x << std::endl;
   x.emplace("TutorialsPoint");
   std::cout << "After emplace: " << * x << std::endl;
   return 0;
}

Output

Output of the above code is as follows −

Before emplace: Welcome
After emplace: TutorialsPoint
cpp_optional.htm
Advertisements