From cppreference.com
template<classT,class...Args>staticvoidconstruct(Alloc&a,T*p,Args&&...args);(since C++11)
(constexpr since C++20)If possible, constructs an object of type T in allocated uninitialized storage pointed to by p, by calling a.construct(p,std::forward<Args>(args)...).
If the above is not possible (e.g. Alloc does not have the member function construct()), then calls
::new(static_cast<void*>(p))T(std::forward<Args>(args)...)
(until C++20)std::construct_at(p,std::forward<Args>(args)...)
(since C++20)Parameters
a - allocator to use for construction p - pointer to the uninitialized storage on which a T object will be constructed args... - the constructor arguments to pass to a.construct() or to placement-new(until C++20)
(since C++20)Notes
This function is used by the standard library containers when inserting, copying, or moving elements.
Because this function provides the automatic fall back to
, the member function construct() is an optional
requirement.
(since C++11)Example
Run this code
#include<memory>structfoo{virtualintbar(){return0;}virtual~foo(){}};intmain(){std::allocator<foo>al;usingtraits=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);}See also