跳到主要内容

std::allocator_traits<Alloc>::construct

自 C++20 起
template< class T, class... Args >
static constexpr void construct( Alloc& a, T* p, Args&&... args );
从 C++11 起,直到 C++20
template< class T, class... Args >
static void construct( Alloc& a, T* p, Args&&... args );

如果可能,通过调用构造一个类型为 T 的对象,在指向 p 的已分配的未初始化存储中。

a.construct(p, std::forward<Args>(args)...)

如果上述情况不可行(例如,Alloc 没有成员函数 construct()),则调用::new (static_cast<void*>(p)) T(std::forward<Args>(args)...)  (直到 C++20)
::new (static_cast<void*>(p)) T(std::forward<Args>(args)...) (自 C++20 起)

参数

a - 用于构造的分配器
p - 指向将构造 T 对象的未初始化存储的指针
args..。- 要传递给 a.construct() placement-new  (直到 C++20) std::construct_at()  (自 C++20 起) 的构造函数参数。

返回值

(无)

备注

标准库容器在插入、复制或移动元素时会使用此函数。

由于此函数提供了自动回退到 placement new 的功能,因此自 C++11 起,成员函数 construct() 是分配器的一个可选要求。

std::allocator_traits<Alloc>::construct

自 C++20 起
template< class T, class... Args >
static constexpr void construct( Alloc& a, T* p, Args&&... args );
从 C++11 起,直到 C++20
template< class T, class... Args >
static void construct( Alloc& a, T* p, Args&&... args );

如果可能,通过调用构造一个类型为 T 的对象,在指向 p 的已分配的未初始化存储中。

a.construct(p, std::forward<Args>(args)...)

如果上述情况不可行(例如,Alloc 没有成员函数 construct()),则调用::new (static_cast<void*>(p)) T(std::forward<Args>(args)...)  (直到 C++20)
::new (static_cast<void*>(p)) T(std::forward<Args>(args)...) (自 C++20 起)

参数

a - 用于构造的分配器
p - 指向将构造 T 对象的未初始化存储的指针
args..。- 要传递给 a.construct() placement-new  (直到 C++20) std::construct_at()  (自 C++20 起) 的构造函数参数。

返回值

(无)

备注

标准库容器在插入、复制或移动元素时会使用此函数。

由于此函数提供了自动回退到 placement new 的功能,因此自 C++11 起,成员函数 construct() 是分配器的一个可选要求。