std::default_delete
可以专门化, 以使 std::unique_ptr
可以 轻松管理需要通过调用某些自定义销毁函数而不是使用delete p;
来销毁的类型。
C++中确保对象由std::shared_ptr
管理的基本上有两种方法:
使用
std::make_shared
或std::allocate_shared
创建一个由共享指针管理的对象。这是首选方式,因为它将需要的内存块(有效负载和引用计数)合并为一个。但是,如果只剩下std::weak_ptr
,则仍然需要引用计数来占用有效负载的内存。
第二种情况,在不提供自定义删除器时,是有趣的:
具体而言,它被定义为使用其自己的未指定类型的删除器,该删除器分别使用delete [] p;
或delete p;
,具体取决于实例化std::shared_ptr
是否用于数组。
摘自n4659(~C++17):
template<class Y> explicit shared_ptr(Y* p);
4 Requires:
Y
shall be a complete type. The expressiondelete[] p
, whenT
is an array type, ordelete p
, whenT
is not an array type, shall have well-defined behavior, and shall not throw exceptions.
5 Effects: WhenT
is not an Array type, constructs ashared_ptr
object that owns the pointerp
. Otherwise, constructs ashared_ptr
that ownsp
and a deleter of an unspecified type that callsdelete[] p
. WhenT
is not an array type, enablesshared_from_this
withp
. If an exception is thrown,delete p
is called whenT
is not an array type,delete[] p
otherwise.
6 Postconditions:use_count() == 1 && get() == p
.
[…]
template<class Y> void reset(Y* p);
3 Effects: Equivalent to
shared_ptr(p).swap(*this)
.
我的问题是:
- 为什么没有明确指定使用
std::default_delete
是一个好的选择? - 如果改变这种情况,是否会导致任何有效的(并且可能有用的)代码出现故障?
- 是否已经有人提出了这样的建议?
delete
(或delete[]
)。我不明白你如何在合法情况下将其专业化为执行其他操作。 - T.C.std::make_shared
或std::allocate_shared
合并两个分配,就不会使用单独的删除器。这只是问题的背景。 - Deduplicator