简体   繁体   English

std :: unique_ptr的“无法解除引用”

[英]“No-throw dereferencing” of std::unique_ptr

I write code in C++ which uses a std::unique_ptr u to handle a std::string resource, and I want to dereference u so that I can pass the std::string to a call of the std::string copy constructor: 我用C ++编写代码,使用std::unique_ptr u来处理std::string资源,我想取消引用u以便我可以将std::string传递给std::string拷贝构造函数的调用:

std::string* copy = new std::string( /*dereference u here*/ );

I know that new or the std::string copy constructor could throw, but this is not my point here. 我知道newstd::string拷贝构造函数可以抛出,但这不是我的观点。 I was just wondering whether dereferencing u could already throw an exception. 我只是想知道解除引用u是否已经抛出异常。 I find it strange that operator* is not marked noexcept while the std::unique_ptr method get is actually marked noexcept . 我发现很奇怪, operator* 没有标记为noexceptstd::unique_ptr方法get实际上标记为noexcept In other words: 换一种说法:

*( u.get() )

is noexcept as a whole while 从根本上说是noexcept

*u

isn't. 不是。 Is this a flaw in the standard? 这是标准中的缺陷吗? I don't get why there could be a difference. 我不明白为什么会有区别。 Any ideas? 有任何想法吗?

unique_ptr::operator*() could involve a call to an operator*() overload for the type you're storing in the unique_ptr . unique_ptr::operator*()可能涉及对您在unique_ptr存储的类型的operator*()重载的调用。 Note that the type stored in a unique_ptr need not be a bare pointer, you can change the type via the nested type D::pointer , where D is the type of the unique_ptr 's deleter . 请注意,存储在unique_ptr中的类型不必是裸指针,您可以通过嵌套类型D::pointer更改类型,其中Dunique_ptr的删除器的类型。 This is why the function is not noexcept . 这就是函数不是noexcept

This caveat doesn't apply to your use case because you're storing an std::string * in the unique_ptr and not some type that overloads operator* . 这个警告不适用于您的用例,因为您在unique_ptr存储了std::string * ,而不是某个重载operator*类型。 So the call is effectively noexcept for you. 所以调用的是有效noexcept你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM