gpt4 book ai didi

c++ - 为什么 std::make_shared 无法编译删除了运算符 new 的类型?

转载 作者:行者123 更新时间:2023-12-02 00:45:28 24 4
gpt4 key购买 nike

我正在尝试编写堆禁止类型,即不可在堆分配的内存上构造的类型。通过删除operator new 和placement new 我想我可以实现这一点。但是使用 std::make_shared 创建共享指针仍然可以编译。

为什么不 std::make_shared<A>()删除新运算符后编译失败?

#include <memory>

class A {
public:
void* operator new(size_t) = delete;
void* operator new(size_t, void*) = delete;
void* operator new [] (size_t) = delete;
};

// Regular new fails
A* a1 = new A();

// Placement new fails
void* pv = std::malloc(sizeof(A));
A* a2 = new (pv) A();

// make_shared works
std::shared_ptr<A> a3 = std::make_shared<A>();

最佳答案

std::make_shared::​new (pv) T(std​::​forward<Args>(args)...) 指定.

[util.smartptr.shared.create]

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.

分配的内存通常是用于控制 block ,而不是直接分配给 new T 。然后通过放置 new 构造该对象,但 new 表达式完全有资格使用全局放置 operator new ,而不是任何特定于类的。

[expr.new]

9 If the new-expression begins with a unary ​:: ​operator, the allocation function's name is looked up in the global scope. Otherwise, if the allocated type is a class type T or array thereof, the allocation function's name is looked up in the scope of T. If this lookup fails to find the name, or if the allocated type is not a class type, the allocation function's name is looked up in the global scope.

这两种用途将完全绕过您的自定义删除运算符。

关于c++ - 为什么 std::make_shared 无法编译删除了运算符 new 的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59795722/

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