std::vector<T,Allocator>:: emplace
|
template
<
class
...
Args
>
iterator emplace ( const_iterator pos, Args && ... args ) ; |
(C++11부터)
(C++20부터 constexpr) |
|
컨테이너에 새 요소를 pos 바로 앞에 직접 삽입합니다.
요소는 일반적으로 컨테이너가 제공하는 위치에서 제자리(in-place)에 요소를 생성하기 위해 placement new 를 사용하는 std::allocator_traits::construct 를 통해 생성됩니다. 그러나 필요한 위치가 기존 요소로 이미 점유된 경우, 삽입된 요소는 먼저 다른 위치에서 생성된 후 필요한 위치로 이동 할당(move assigned)됩니다.
인수들 args... 는 생성자에게 std:: forward < Args > ( args ) ... 로 전달됩니다. args... 는 컨테이너 내의 값을 직접 또는 간접적으로 참조할 수 있습니다.
만약 연산 후 새로운
size()
가 기존
capacity()
보다 크면 재할당이 발생하며, 이 경우 모든 반복자(including the
end()
iterator)와 모든 요소에 대한 참조가 무효화됩니다. 그렇지 않으면 삽입 지점 이전의 반복자와 참조만 유효하게 유지됩니다.
목차매개변수
반환값삽입된 요소를 가리키는 반복자. 복잡도pos 와 end() 사이의 거리에 선형적입니다. 예외
복사 생성자, 이동 생성자, 할당 연산자, 또는 이동 할당 연산자 이외의 이유로 예외가 발생하거나,
그렇지 않으면, 효과는 지정되지 않습니다. 예제
이 코드 실행
#include <iostream> #include <string> #include <vector> struct A { std::string s; A(std::string str) : s(std::move(str)) { std::cout << " constructed\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::vector<A> container; // reserve enough place so vector does not have to resize container.reserve(10); std::cout << "construct 2 times A:\n"; A two{"two"}; A three{"three"}; std::cout << "emplace:\n"; container.emplace(container.end(), "one"); std::cout << "emplace with A&:\n"; container.emplace(container.end(), two); std::cout << "emplace with A&&:\n"; container.emplace(container.end(), std::move(three)); std::cout << "content:\n"; for (const auto& obj : container) std::cout << ' ' << obj.s; std::cout << '\n'; } 출력: construct 2 times A: constructed constructed emplace: constructed emplace with A&: copy constructed emplace with A&&: move constructed content: one two three 결함 보고서다음의 동작 변경 결함 보고서들은 이전에 발표된 C++ 표준에 소급 적용되었습니다.
참고 항목
| ||||||||||||||||||||||||