Namespaces
Variants

std::vector<T,Allocator>:: emplace

From cppreference.net

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 - 새로운 요소가 생성될 위치의 앞 반복자
args - 요소의 생성자로 전달할 인자들
타입 요구사항
-
다음 조건 중 하나라도 만족될 경우 동작은 정의되지 않음:

반환값

삽입된 요소를 가리키는 반복자.

복잡도

pos end() 사이의 거리에 선형적입니다.

예외

복사 생성자, 이동 생성자, 할당 연산자, 또는 이동 할당 연산자 이외의 이유로 예외가 발생하거나, T CopyInsertable 이거나 nothrow 이동 생성 가능한 경우 끝에 단일 요소를 삽입하기 위해 emplace 를 사용하는 동안 예외가 발생하면, 아무런 영향이 없습니다 (강력한 예외 보장).

그렇지 않으면, 효과는 지정되지 않습니다.

예제

#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++ 표준에 소급 적용되었습니다.

DR 적용 대상 게시된 동작 올바른 동작
LWG 2164 C++11 인수가 컨테이너를 참조할 수 있는지 여부가 불분명했음 명확히 규정됨

참고 항목

요소 삽입
(public member function)
요소를 제자리에 생성하여 끝에 추가
(public member function)