std::optional<T>::emplace

From cppreference.com
< cpp‎ | utility‎ | optional
 
 
Utilities library
General utilities
Date and time
Function objects
Formatting library (C++20)
(C++11)
Relational operators (deprecated in C++20)
Integer comparison functions
(C++20)
Swap and type operations
(C++14)
(C++11)
(C++11)
(C++11)
(C++17)
Common vocabulary types
(C++11)
(C++17)
(C++17)
(C++17)
(C++17)

Elementary string conversions
(C++17)
(C++17)
 
 
template< class... Args >
T& emplace( Args&&... args );
(1) (since C++17)
template< class U, class... Args >
T& emplace( std::initializer_list<U> ilist, Args&&... args );
(2) (since C++17)

Constructs the contained value in-place. If *this already contains a value before the call, the contained value is destroyed by calling its destructor.

1) Initializes the contained value by direct-initializing (but not direct-list-initializing) with std::forward<Args>(args)... as parameters.
2) Initializes the contained value by calling its constructor with ilist, std::forward<Args>(args)... as parameters. This overload only participates in overload resolution if std::is_constructible<T, std::initializer_list<U>&, Args&&...>::value is true.

Parameters

args... - the arguments to pass to the constructor
ilist - the initializer list to pass to the constructor
Type requirements
-
T must be constructible from Args... for overload (1)
-
T must be constructible from std::initializer_list and Args... for overload (2)

Return value

A reference to the new contained value.

Exceptions

Any exception thrown by the selected constructor of T. If an exception is thrown, *this does not contain a value after this call (the previously contained value, if any, had been destroyed).

Example

#include <optional>
#include <iostream>
 
struct A {
    std::string s;
    A(std::string str) : s(std::move(str))  { std::cout << " constructed\n"; }
    ~A() { std::cout << " destructed\n"; }
    A(const A& o) : s(o.s) { std::cout << " copy constructed\n"; }
    A(A&& o) : s(std::move(o.s)) { std::cout << " move constructed\n"; }
    A& operator=(const A& other) {
        s = other.s;
        std::cout << " copy assigned\n";
        return *this;
    }
    A& operator=(A&& other) {
        s = std::move(other.s);
        std::cout << " move assigned\n";
        return *this;
    }
};
 
int main()
{
    std::optional<A> opt;
 
    std::cout << "Assign:\n";
    opt = A("Lorem ipsum dolor sit amet, consectetur adipiscing elit nec.");
 
    std::cout << "Emplace:\n";
    // As opt contains a value it will also destroy that value
    opt.emplace("Lorem ipsum dolor sit amet, consectetur efficitur. ");
 
    std::cout << "End example\n";
}

Output:

Assign:
 constructed
 move constructed
 destructed
Emplace:
 destructed
 constructed
End example
 destructed

See also

assigns contents
(public member function)