我想编写一个调用 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 templateallocate_shared
uses a copy ofa
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/