std::list<T,Allocator>:: emplace_back
|
template
<
class
...
Args
>
void emplace_back ( Args && ... args ) ; |
(C++17 이전) | |
|
template
<
class
...
Args
>
reference emplace_back ( Args && ... args ) ; |
(C++17 이후)
(C++26부터 constexpr) |
|
컨테이너의 끝에 새로운 요소를 추가합니다. 요소는 std::allocator_traits::construct 를 통해 생성되며, 일반적으로 컨테이너가 제공하는 위치에서 인-플레이스(in-place) 방식으로 요소를 생성하기 위해 placement new 를 사용합니다. 인자 args... 는 생성자에게 std:: forward < Args > ( args ) ... 형태로 전달됩니다.
반복자나 참조가 무효화되지 않습니다.
목차 |
매개변수
| args | - | 요소의 생성자로 전달할 인수들 |
| 타입 요구사항 | ||
-
T
가
EmplaceConstructible
(으로부터
args...
를 사용하여
list
에)가 아니라면, 동작은 정의되지 않습니다.
|
||
반환값
|
(없음) |
(until C++17) |
|
삽입된 요소에 대한 참조. |
(since C++17) |
복잡도
상수.
예외
어떤 이유로든 예외가 발생하면, 이 함수는 아무런 효과를 가지지 않습니다( strong exception safety guarantee ).
예제
다음 코드는
emplace_back
을 사용하여
President
타입의 객체를
std::list
에 추가합니다. 이 코드는
emplace_back
이 매개변수를
President
생성자로 전달하는 방식을 보여주며,
emplace_back
을 사용하면
push_back
을 사용할 때 필요한 추가적인 복사나 이동 연산을 피할 수 있음을 보여줍니다.
#include <list> #include <cassert> #include <iostream> #include <string> struct President { std::string name; std::string country; int year; President(std::string p_name, std::string p_country, int p_year) : name(std::move(p_name)), country(std::move(p_country)), year(p_year) { std::cout << "I am being constructed.\n"; } President(President&& other) : name(std::move(other.name)), country(std::move(other.country)), year(other.year) { std::cout << "I am being moved.\n"; } President& operator=(const President& other) = default; }; int main() { std::list<President> elections; std::cout << "emplace_back:\n"; auto& ref = elections.emplace_back("Nelson Mandela", "South Africa", 1994); assert(ref.year == 1994 && "uses a reference to the created object (C++17)"); std::list<President> reElections; std::cout << "\npush_back:\n"; reElections.push_back(President("Franklin Delano Roosevelt", "the USA", 1936)); std::cout << "\nContents:\n"; for (const President& president: elections) std::cout << president.name << " was elected president of " << president.country << " in " << president.year << ".\n"; for (const President& president: reElections) std::cout << president.name << " was re-elected president of " << president.country << " in " << president.year << ".\n"; }
출력:
emplace_back: I am being constructed. push_back: I am being constructed. I am being moved. Contents: Nelson Mandela was elected president of South Africa in 1994. Franklin Delano Roosevelt was re-elected president of the USA in 1936.
참고 항목
|
끝에 요소를 추가합니다
(public member function) |
|
|
(C++11)
|
제자리에서 요소를 생성합니다
(public member function) |