gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 01:43:07 29 4
gpt4 key购买 nike

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

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

boost::shared_ptr<Object> object = boost::allocate_shared<Object> (CustomAllocator ());

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

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

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

最佳答案

至于std::allocate_shared就此而言,您看到的行为是正确的。引用 C++11 [util.smartptr.shared.create]:

template<class T, class... Args> shared_ptr<T> make_shared(Args&&... args);
template<class T, class A, class... Args>
shared_ptr<T> allocate_shared(const A& a, Args&&... args);

2 Effects: 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>(args)...). The template allocate_shared uses a copy of a to allocate memory. If an exception is thrown, the functions have no effect.

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

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

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

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com