std::optional<T>::emplace
cppreference.net에서
template< class... Args >
T& emplace( Args&&... args );
|
(1) | (C++17부터) (C++20부터 constexpr) |
template< class U, class... Args >
T& emplace( std::initializer_list<U> ilist, Args&&... args );
|
(2) | (C++17부터) (C++20부터 constexpr) |
포함된 값을 제자리에 생성합니다. 호출 전에 *this가 이미 값을 포함하고 있으면, 포함된 값은 소멸자를 호출하여 파괴됩니다.
1) 직접 초기화(direct-initializing) (단, 직접 리스트 초기화(direct-list-initializing)는 아님)를 통해 포함된 값을
std::forward<Args>(args)...를 매개변수로 초기화합니다.2)
ilist, std::forward<Args>(args)...을 매개변수로 생성자를 호출하여 포함된 값을 초기화합니다. 이 오버로드는 std::is_constructible<T, std::initializer_list<U>&, Args&&...>::value이 true인 경우에만 오버로드 해결에 참여합니다.매개변수
| args... | - | 생성자에 전달할 인수들 |
| ilist | - | 생성자에 전달할 초기화 리스트 |
| 타입 요구사항 | ||
-
T
는
Args...
로부터 생성 가능해야 함 (오버로드
(1)
용)
|
||
-
T
는
std::initializer_list
와
Args...
로부터 생성 가능해야 함 (오버로드
(2)
용)
|
||
반환값
새로운 포함된 값에 대한 참조.
예외
T
의 선택된 생성자에 의해 발생하는 모든 예외. 예외가 발생하면,
*
this
는 이 호출 이후 값을 포함하지 않습니다 (이전에 포함된 값이 있었다면 파괴되었습니다).
| 기능 테스트 매크로 | 값 | 표준 | 기능 |
|---|---|---|---|
__cpp_lib_optional
|
202106L
|
(C++20)
(DR20) |
완전한 constexpr ( 1,2 ) |
예제
이 코드 실행
#include <iostream> #include <optional> struct A { std::string s; A(std::string str) : s(std::move(str)), id{n++} { note("+ constructed"); } ~A() { note("~ destructed"); } A(const A& o) : s(o.s), id{n++} { note("+ copy constructed"); } A(A&& o) : s(std::move(o.s)), id{n++} { note("+ move constructed"); } A& operator=(const A& other) { s = other.s; note("= copy assigned"); return *this; } A& operator=(A&& other) { s = std::move(other.s); note("= move assigned"); return *this; } inline static int n{}; int id{}; void note(auto s) { std::cout << " " << s << " #" << id << '\n'; } }; 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"; }
출력:
Assign: + constructed #0 + move constructed #1 ~ destructed #0 Emplace: ~ destructed #1 + constructed #2 End example ~ destructed #2
결함 보고서
다음의 동작 변경 결함 보고서들은 이전에 발표된 C++ 표준에 소급 적용되었습니다.
| DR | 적용 대상 | 게시된 동작 | 올바른 동작 |
|---|---|---|---|
| P2231R1 | C++20 |
emplace
가
constexpr
가 아니었으나 C++20에서 필요한 연산들이
constexpr
일 수 있음
|
constexpr 로 변경됨 |
참고 항목
|
내용을 할당
(public member function) |