为什么shared_ptr< void>不专业? [英] Why is shared_ptr<void> not specialized?

查看:93
本文介绍了为什么shared_ptr< void>不专业?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

shared_ptr<void>的特殊之处在于,根据定义,它会通过在void*上调用delete来调用未定义的行为.

shared_ptr<void> is special in that it, by definiton, will invoke undefined behavior by calling delete on a void*.

那么,为什么没有shared_ptr<void>专业化会引发编译错误?

So, why is there not a shared_ptr<void> specialization which throws a compile error?

推荐答案

shared_ptr<T>的特殊之处在于,根据设计,它允许保存指向可转换为T*的任何指针类型的指针,并将使用适当的删除器没有UB!这在shared_ptr<Base> p(new Derived);方案中起作用,但还包括shared_ptr<void>.

shared_ptr<T> is special in that it is by design allowed to hold a pointer to any pointer type which is convertible to T* and will use the proper deleter without UB! This comes into play with shared_ptr<Base> p(new Derived); scenarios, but also includes shared_ptr<void>.

例如:

#include <boost/shared_ptr.hpp>

struct T {
    T() { std::cout << "T()\n"; }
    ~T() { std::cout << "~T()\n"; }
};


int main() {
    boost::shared_ptr<void> sp(new T);
}

产生输出:

$ ./test
T()
~T()

如果您访问 http://www.boost.org /doc/libs/1_47_0/libs/smart_ptr/shared_ptr.htm ,向下滚动至作业部分以查看正在演示的内容.参见 http://www.boost.org/doc/libs/1_47_0/libs/smart_ptr/sp_techniques.html#pvoid 了解更多详细信息.

If you visit http://www.boost.org/doc/libs/1_47_0/libs/smart_ptr/shared_ptr.htm, scroll down to the assignment section to see the very thing being demonstrated. See http://www.boost.org/doc/libs/1_47_0/libs/smart_ptr/sp_techniques.html#pvoid for more details.

EDIT ,如果传递给构造函数的指针类型是void *指针,则 UB.感谢您指出这一点!

EDIT as noted by trinithis, it is UB if the pointer type passed into the constructor is a void * pointer. Thanks for pointing that out!

这篇关于为什么shared_ptr&lt; void&gt;不专业?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆