std :: make_shared()是否使用自定义分配器?

Mar*_*cia 17 c++ shared-ptr make-shared c++11

考虑以下代码:

#include <memory>
#include <iostream>


class SomeClass {
public:
    SomeClass() {
        std::cout << "SomeClass()" << std::endl;
    }

    ~SomeClass() {
        std::cout << "~SomeClass()" << std::endl;
    }

    void* operator new(std::size_t size) {
        std::cout << "Custom new" << std::endl;
        return ::operator new(size);
    }

    void operator delete(void* ptr, std::size_t size) {
        std::cout << "Custom delete" << std::endl;
        ::operator delete(ptr);
    }
};



int main() {
    std::shared_ptr<SomeClass> ptr1(new SomeClass);
    std::cout << std::endl << "Another one..." << std::endl << std::endl;
    std::shared_ptr<SomeClass> ptr2(std::make_shared<SomeClass>());
    std::cout << std::endl << "Done!" << std::endl << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

这是它的输出:

Custom new
SomeClass()

Another one...

SomeClass()

Done!

~SomeClass()
~SomeClass()
Custom delete
Run Code Online (Sandbox Code Playgroud)

显然,std::make_shared()没有给new操作员打电话- 它使用的是自定义分配器.这是标准行为std::make_shared()吗?

Mat*_*Mat 16

是的,这是标准行为.从标准(§20.7.2.2.6shared_ptr 创建):

效果:分配适合T类型对象的内存,并通过放置新表达式在该内存中构造对象 ::new (pv) T(std::forward<Args>(args)...).

make_shared由于效率原因,这允许在单个分配中为共享指针本身("控制块")分配对象和数据结构的存储.

std::allocate_shared如果要控制存储分配,可以使用.

  • `std :: allocate_shared(const A&,Args && ...)`也值得一提.第一个参数是调用`A :: allocate`的分配器. (4认同)

Jon*_*ely 5

为了扩展 Mat 的正确答案,make_shared通常通过分配一个包含shared_ptr引用计数和未初始化字节缓冲区的对象来实现:

template<typename T>
  struct shared_count_inplace
  {
    long m_count;
    long weak_count;
    typename std::aligned_storage<sizeof(T)>::type m_storage;
    // ...
  };
Run Code Online (Sandbox Code Playgroud)

这是将在堆上分配的类型,而不是您的类型,因此new不会调用您的类型。然后您的类型将使用位置new处的放置来构建(void*)&m_storage