From cppreference.com
template<class...Args>T&emplace(Args&&...args); (1)(since C++17)
(constexpr since C++20)template<classU,class...Args>T&emplace(std::initializer_list<U>ilist,Args&&...args); (2)(since C++17)
(constexpr since C++20)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
(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 participates in overload resolution only 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
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).
macro ValueStdFeature
(C++20)
(DR20)Fully constexpr(
)Example
Run this code
#include<iostream>#include<optional>structA{std::strings;A(std::stringstr):s(std::move(str)),id{n++}{note("+ constructed");}~A(){note("~ destructed");}A(constA&o):s(o.s),id{n++}{note("+ copy constructed");}A(A&&o):s(std::move(o.s)),id{n++}{note("+ move constructed");}A&operator=(constA&other){s=other.s;note("= copy assigned");return*this;}A&operator=(A&&other){s=std::move(other.s);note("= move assigned");return*this;}inlinestaticintn{};intid{};voidnote(autos){std::cout<<" "<<s<<" #"<<id<<'\n';}};intmain(){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 valueopt.emplace("Lorem ipsum dolor sit amet, consectetur efficitur.");std::cout<<"End example\n";}Output:
Assign: + constructed #0 + move constructed #1 ~ destructed #0 Emplace: ~ destructed #1 + constructed #2 End example ~ destructed #2 Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
DR Applied to Behavior as published Correct behavior
C++20 emplace was not constexpr while the required operations can be constexpr in C++20 made constexprSee also