std::allocate_shared
Defined in header <memory> | | |
|---|---|---|
template< class T, class Alloc, class... Args > shared_ptr<T> allocate_shared( const Alloc& alloc, Args&&... args ); | | (since C++11) |
构造类型的对象。T并将其包装在std::shared_ptr使用args的构造函数的参数列表。T对象的构造方式就像由表达式构造一样。::new(pv) T(std::forward<Args>(args)...),在哪里pv是内部的void*指向适于保存类型对象的存储的指针。T存储空间通常大于sizeof(T)为了对共享指针的控制块和T对象。
所有内存分配都使用alloc,它必须满足Allocator所需经费。
大std::shared_ptr此函数调用的构造函数启用shared_from_this具有指向新构造的类型对象的指针。T...
参数
alloc | - | The Allocator to use. |
|---|---|---|
args... | - | list of arguments with which an instance of T will be constructed. |
返回值
std::shared_ptr类型实例的T...
例外
引发的异常。Alloc::allocate()的构造函数T如果抛出异常,则此函数没有任何效果。
注记
就像std::make_shared,此函数通常只执行一次分配,并将两个T对象和标准建议的分配内存块%28中的控制块(但不需要此要求),所有已知实现都执行此%29。一份alloc作为控制块的一部分存储,以便一旦共享和弱引用计数达到零时,就可以使用它来释放它。
与STD::Shared不同[医]PTR构造函数,STD::[医]Shared不接受单独的自定义删除器:提供的分配器用于销毁控制块,而T对象,并对它们的共享内存块进行去分配。
std::shared_ptr支持C++17%29的数组类型%28 A,但是std::allocate_shared不会的。支持此功能。助推::分配[医]共享...
构造者使shared_from_this用指针ptr类型U*意味着它决定U具有明确和可访问的基类,该基类是std::enable_shared_from_this,如果是这样,构造函数将计算语句:
二次
if (ptr != nullptr && ptr->weak_this.expired())
ptr->weak_this = std::shared_ptr<std::remove_cv_t<U>>(*this,
const_cast<std::remove_cv_t<U>*>(ptr));二次
何地weak_this是隐藏的可变的std::weak_ptr成员std::shared_from_this.给弱者的任务[医]该成员不是原子成员,并且与对同一对象的任何可能并发访问相冲突。这确保了将来调用shared_from_this()将与shared_ptr由此原始指针构造函数创建。
试验ptr->weak_this.expired()在上面的解说代码中,确保弱[医]如果它已经指示了所有者,则不会重新分配。从C++17开始,就需要进行此测试。
另见
(constructor) | constructs new shared_ptr (public member function) |
|---|---|
make_shared | creates a shared pointer that manages a new object (function template) |
© cppreference.com在CreativeCommonsAttribution下授权-ShareAlike未移植许可v3.0。
本文档系腾讯云开发者社区成员共同维护,如有问题请联系 cloudcommunity@tencent.com

