gpt4 book ai didi

c++ - 如果 unique_ptr 需要存储删除器,它怎么能没有开销?

转载 作者:IT老高 更新时间:2023-10-28 12:52:52 25 4
gpt4 key购买 nike

首先看看 C++ Primer 说的 unique_ptrshared_ptr :
16.1.6 美元。效率和灵 active

We can be certain that shared_ptr does not hold the deleter as a direct member, because the type of the deleter isn’t known until run time.

Because the type of the deleter is part of the type of a unique_ptr, the type of the deleter member is known at compile time. The deleter can be stored directly in each unique_ptr object.

所以看起来 shared_ptr没有 deleter 的直接成员,但是 unique_ptr做。但是,the top-voted answer of another question说:

If you provide the deleter as template argument (as in unique_ptr) it is part of the type and you don't need to store anything additional in the objects of this type. If deleter is passed as constructor's argument (as in shared_ptr) you need to store it in the object. This is the cost of additional flexibility, since you can use different deleters for the objects of the same type.

引用的两个段落完全冲突,这让我感到困惑。更重要的是,many people says unique_ptr is zero overhead因为它不需要将删除器存储为成员。然而,正如我们所知,unique_ptr具有 unique_ptr<obj,del> p(new obj,fcn) 的构造函数,这意味着我们可以传递一个删除器给它,所以 unique_ptr似乎已将删除器存储为成员。真是一团糟!

最佳答案

std::unique_ptr<T>很可能是零开销(任何理智的标准库实现)。 std::unique_ptr<T, D> , 对于任意 D , 通常不是零开销。

原因很简单:空基优化可用于消除删除器的存储,以防删除器为空(因此是无状态)类型(例如 std::default_delete 实例化)。

关于c++ - 如果 unique_ptr 需要存储删除器,它怎么能没有开销?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50001598/

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