为什么std :: shared_ptr取消引用不会引发空指针异常(或类似的异常)? [英] Why doesn't std::shared_ptr dereference throw a null pointer exception (or similar)?

查看:197
本文介绍了为什么std :: shared_ptr取消引用不会引发空指针异常(或类似的异常)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

异常是C ++的重要组成部分,使用它的原因之一(我知道还有很多,更重要的其他原因)是避免不必要的检查,这些检查会使大量的混淆代码语句(也许这是一个错误的假设?)。

Exceptions are a big part of C++ and one of the reasons to use it (I know there are many, more important, other reasons) is to avoid needless checks that obfuscate code with a lot of if statements (maybe this is an incorrect assumption?).

所以现在我很好奇为什么 std :: shared_ptr :: operator * std :: shared_ptr :: operator-> 不会抛出 null_ptr_exception 或类似的东西?

So now I am curious as to why std::shared_ptr::operator* and std::shared_ptr::operator-> do not throw a null_ptr_exception or similar?

推荐答案

我的理解是,智能指针类的设计和行为类似于原始指针。有了这个指导性的设计原则,理想情况下,遗留代码可以使用等效的所有权语义简单地用智能指针替换原始指针的使用,并且代码将像以前一样正常工作。

My understanding is that the smart pointer classes are designed to look and behave like raw pointers. Given this guiding design principal, ideally legacy code could simply replace usage of raw pointers with smart pointers using equivalent ownership semantics and the code would work exactly as before.

因此,更改取消引用智能指针的行为不应执行任何其他检查或引发异常(即,由于原始指针不会以这种方式运行)。

Therefore, changing the behavior for dereferencing smart pointers should not do any additional checks or throw exceptions (i.e., since raw pointers don't behave this way).

添加智能指针的建议表示该设计决策(将通用智能指针添加到图书馆技术报告中):

The proposal to add smart pointers to the standard indicates this design decision (A Proposal to Add General Purpose Smart Pointers to the Library Technical Report):


III。设计决策

III. Design Decisions

A。一般原则


  1. 尽可能接近原始指针,但不要更接近


这篇关于为什么std :: shared_ptr取消引用不会引发空指针异常(或类似的异常)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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