Namespaces
Variants

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

From cppreference.net

template < class ... Args >
iterator emplace ( const_iterator pos, Args && ... args ) ;
(C++11부터)
(C++26부터 constexpr)

컨테이너에 새 요소를 pos 바로 앞에 직접 삽입합니다.

요소는 std::allocator_traits::construct 를 통해 생성되며, 이는 컨테이너가 제공한 위치에서 new 배치를 사용하여 요소를 제자리에서 생성합니다.

인수들 args... 는 생성자에게 std:: forward < Args > ( args ) ... 로 전달됩니다. args... 는 직접적으로 또는 간접적으로 컨테이너 내의 값을 참조할 수 있습니다.

반복자나 참조가 무효화되지 않습니다.

목차

매개변수

pos - 새로운 요소가 생성될 위치의 이전 반복자
args - 요소의 생성자로 전달할 인자들
타입 요구사항
-
만약 T EmplaceConstructible 가 아니거나 list args... 로부터 생성할 수 없는 경우, 동작은 정의되지 않음

반환값

배치된 요소를 가리키는 반복자.

복잡도

상수.

예외

예외가 발생하면(예: 생성자에 의해), 이 함수가 호출되지 않은 것처럼 컨테이너는 수정되지 않은 상태로 유지됩니다(강력한 예외 보장).

예제

#include <iostream>
#include <string>
#include <list>
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::list<A> container;
    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)