◐ Shell
clean mode source ↗

std::allocator_traits<Alloc>::construct - cppreference.com

来自cppreference.com

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

若可能,则在 p 所指向的分配的未初始化存储构造 T 类型对象,通过调用 a.construct(p, std::forward<Args>(args)...) 进行。

若以上不可行(例如 Allocconstruct() 成员函数),则调用

::new (static_cast<void*>(p)) T(std::forward<Args>(args)...)

(C++20 前)

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

(C++20 起)

参数

a - 用于构造的分配器
p - 指向未初始化存储的指针,将在其上构造 T 对象
args... - 传递给 a.construct()布置 new(C++20 前) std::construct_at()(C++20 起) 的构造函数实参

注解

此函数为标准库容器在插入、复制或移动元素时所用。 {{rrev|since=c++11|1= 因为此函数提供到布置 new 的自动后备,故成员函数 construct()分配器 (Allocator) 的可选要求。

示例

#include <memory>

struct foo
{
    virtual int bar() { return 0; }
    virtual ~foo() {}
};

int main()
{
    std::allocator<foo> al;
    using traits = std::allocator_traits<decltype(al)>;
    foo* p = traits::allocate(al, 1);
    traits::construct(al, p);
    p->bar();
    traits::destroy(al, p);
    traits::deallocate(al, p, 1);
}
}

参阅