sách gpt4 ăn đã đi

c++ - 为什么 boost::allocate_shared (alloc) 忽略 alloc.construct() 并且 std::allocate_shared (alloc) 表现相似?

In lại 作者:搜寻专家 更新时间:2023-10-31 01:43:07 32 4
mua khóa gpt4 giày nike

我想编写一个调用 createHook() 的自定义分配器在对象构造和对称之后 destroyHook()就在对象销毁之前。我以这种方式使用我的分配器:

class Object {};
class CustomAllocator { /* ... */ };

boost::shared_ptr object = boost::allocate_shared (CustomAllocator ());

同时 allocate_shared<>正确调用 allocate()在我的分配器上,它确实使用了就地 mới语句而不是调用 construct()在我的分配器上。

我知道如何通过编写自定义 my_allocate_shared() 来规避这个问题。调用 createHook() 的版本并返回 shared_ptr<>带有自定义删除器的实例(依次调用 destroyHook() ),但我丢失了 allocate_shared<>然后优化。

我的编码环境仅限于C++03,所以我不知道如何std::allocate_shared()在 C++11 上下文中表现(或应该表现)。

câu trả lời hay nhất

Đối vớistd::allocate_shared就此而言,您看到的行为是正确的。引用 C++11 [util.smartptr.shared.create]:

template shared_ptr make_shared(Args&&... args);
template
shared_ptr allocate_shared(const A& a, Args&&... args);

2 Các hiệu ứng: Allocates memory suitable for an object of type T and constructs an object in that memory via the placement new expression ::new (pv) T(std::forward(args)...). The template allocate_shared uses a copy of Một to allocate memory. If an exception is thrown, the functions have no effect.

由于标准库共享指针支持主要基于 Boost 实现,我认为 Boost 的行为类似是有道理的。

正如@KerrekSB 在评论中指出的那样,显然有一个标准库 active issue 2070关于这个。

关于c++ - 为什么 boost::allocate_shared (alloc) 忽略 alloc.construct() 并且 std::allocate_shared (alloc) 表现相似?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25804018/

32 4 0
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress