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

标签 c++ c++11 shared-ptr make-shared

考虑 this code :

#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;
}

这是它的输出:

Custom new
SomeClass()

Another one...

SomeClass()

Done!

~SomeClass()
~SomeClass()
Custom delete

显然,std::make_shared() 没有调用 new 运算符——它使用的是自定义分配器。这是 std::make_shared() 的标准行为吗?

最佳答案

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

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)...).

这允许 make_shared出于效率原因,在一次分配中为共享指针本身(“控制 block ”)分配对象和数据结构的存储空间。

您可以使用 std::allocate_shared 如果您想控制该存储分配。

关于c++ - std::make_shared() 是否使用自定义分配器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14080408/

相关文章:

c++ - 强制转换和 namespace 运算符之间没有空格?

c++ - 为什么不应该直接访问 __m128i 字段?

c++ - 生成 makefile 时不包含 cmake c++11 标志

C++ 如何将对象添加到 map 并返回对 map 内新创建的对象的引用

c++ - 什么是未知大小的 make_shared?

java - 高性能流数据处理问题

c++ - 在 C++ 中对整数数组进行线性搜索时,SSE 比较无法按预期工作

templates - 模板中标记为 boost::bimap - 它们有效吗?

c++ - 对于 wchar_t 来说,char(0) 或 '\0' 等价于什么?

c++ - 如何将 boost::tuple 分配给 boost::shared_ptr