piecewise_construct — std::piecewise_construct
piecewise_construct — std::piecewise_construct
std::piecewise_construct(및 std::piecewise_construct_t)는 std::pair를 만들 때 각 원소를 별도의 인자 목록(tuple)으로 "조각별" 생성하라는 신호를 주는 태그예요. C++11에서 도입됐어요. <utility> 헤더에 있어요.
pair의 원소를 배치 생성(복사·이동 없이 직접 생성)할 때 사용해요.
출처: cppreference
본문
// <utility> 헤더, C++11
struct piecewise_construct_t { explicit piecewise_construct_t() = default; };
inline constexpr std::piecewise_construct_t piecewise_construct{};
사용 예 — pair 원소 배치 생성
#include <utility>
#include <string>
#include <map>
// pair의 각 원소를 tuple 인자로 직접 생성
std::pair<std::string, int> p(
std::piecewise_construct,
std::forward_as_tuple("hello"), // first를 "hello"로
std::forward_as_tuple(42) // second를 42로
);
왜 쓰는가 — 복사 불가 타입
원소가 복사·이동 불가하면 중간 임시 없이 배치 생성해야 해요.
#include <utility>
#include <tuple>
#include <map>
struct NoCopy {
explicit NoCopy(int) {}
NoCopy(const NoCopy&) = delete;
};
std::map<int, NoCopy> m;
// 임시 없이 배치 생성 (piecewise_construct 사용)
m.emplace(std::piecewise_construct,
std::forward_as_tuple(1),
std::forward_as_tuple(100));
효율
임시 pair를 만들었다가 복사/이동하는 대신, 목적지에 직접 생성해 오버헤드를 줄여요.
std::piecewise_construct는 std::pair의 두 원소를 서로 다른 생성자 인자 목록으로 배치 생성하고 싶을 때 쓰는 태그예요. 특히 복사 불가한 원소나 map의 emplace에서 유용해요.