gpt4 book ai didi

c++ - 为什么 shared_ptr 合法,而 unique_ptr 格式不正确?

转载 作者:IT老高 更新时间:2023-10-28 11:58:35 27 4
gpt4 key购买 nike

这个问题确实符合标题:我很想知道造成这种差异的技术原因是什么,以及基本原理?

std::shared_ptr<void> sharedToVoid; // legal;
std::unique_ptr<void> uniqueToVoid; // ill-formed;

最佳答案

这是因为 std::shared_ptr 实现了类型删除,而 std::unique_ptr 没有。


由于 std::shared_ptr 实现了类型删除,它还支持 另一个 有趣的属性,即。它确实需要删除器的类型作为模板类型参数到类模板。看看他们的声明:

template<class T,class Deleter = std::default_delete<T> > 
class unique_ptr;

其中有 Deleter 作为类型参数,而

template<class T> 
class shared_ptr;

没有。

那么,shared_ptr 为什么要实现类型删除?

嗯,它这样做了,因为它必须支持引用计数,并且为了支持这一点,它必须从堆中分配内存,并且因为它必须无论如何都要分配内存,所以它向前迈了一步进一步并实现类型删除——这也需要堆分配。 所以基本上就是投机取巧!

由于类型删除,std::shared_ptr 能够支持两件事:

  • 它可以将任何类型的对象存储为 void*但它仍然能够正确地删除销毁时的对象通过正确调用它们的析构函数
  • 删除器的类型不作为类型参数传递给类模板,这意味着有一点自由不影响类型安全

好的。这就是 std::shared_ptr 的工作原理。

现在的问题是,std::unique_ptr 可以存储对象as void* 吗?好吧,答案是,是的——只要你传递一个合适的删除器作为参数。这是一个这样的演示:

int main()
{
auto deleter = [](void const * data ) {
int const * p = static_cast<int const*>(data);
std::cout << *p << " located at " << p << " is being deleted";
delete p;
};

std::unique_ptr<void, decltype(deleter)> p(new int(959), deleter);

} //p will be deleted here, both p ;-)

输出(online demo):

959 located at 0x18aec20 is being deleted

你在评论中问了一个非常有趣的问题:

In my case I will need a type erasing deleter, but it seems possible as well (at the cost of some heap allocation). Basically, does this mean there is actually a niche spot for a 3rd type of smart pointer: an exclusive ownership smart pointer with type erasure.

@Steve Jessop建议以下解决方案,

I've never actually tried this, but maybe you could achieve that by using an appropriate std::function as the deleter type with unique_ptr? Supposing that actually works then you're done, exclusive ownership and a type-erased deleter.

按照这个建议,我实现了这个(虽然它没有使用 std::function,因为它似乎没有必要):

using unique_void_ptr = std::unique_ptr<void, void(*)(void const*)>;

template<typename T>
auto unique_void(T * ptr) -> unique_void_ptr
{
return unique_void_ptr(ptr, [](void const * data) {
T const * p = static_cast<T const*>(data);
std::cout << "{" << *p << "} located at [" << p << "] is being deleted.\n";
delete p;
});
}

int main()
{
auto p1 = unique_void(new int(959));
auto p2 = unique_void(new double(595.5));
auto p3 = unique_void(new std::string("Hello World"));
}

输出(online demo):

{Hello World} located at [0x2364c60] is being deleted.
{595.5} located at [0x2364c40] is being deleted.
{959} located at [0x2364c20] is being deleted.

希望对您有所帮助。

关于c++ - 为什么 shared_ptr<void> 合法,而 unique_ptr<void> 格式不正确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39288891/

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