c++ - 为什么 boost::allocate_shared<T> (alloc) 忽略 alloc.construct() 和 std::allocate_shared<T> (alloc) 行为相似?

标签 c++ boost shared-ptr allocator

我想编写一个调用 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/

相关文章:

c++ - Uniform_real 不接受 numeric_limits::lowest()

c++ - 使用 bzip boost iostream - 未解析的符号

C++ 对shared_ptrs vector 进行排序

c++ - 向下指针键入与 shared_ptr 一起使用的级别

c++ - 指向右值的指针

c++ - 函数采用具有默认值的引用参数

c++ - 如何在 C++ 中导出注册表项

c++ - 如何将这个 Boost ASIO 示例应用到我的应用程序中

c++ - 解析问题c++

c++ - 将 Boost 与 CMake 链接时出错