[英]“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. 我知道
new
或std::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*
没有标记为noexcept
而std::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
更改类型,其中D
是unique_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.