“无抛出取消引用”; std :: unique_ptr的 [英] "No-throw dereferencing" of std::unique_ptr
问题描述
我用C ++编写代码,该代码使用 std :: unique_ptr u
处理 std :: string
资源,并且我想取消引用 u
,以便可以将 std :: string
传递给<$的调用c $ c> std :: string 复制构造函数:
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:
std::string* copy = new std::string( /*dereference u here*/ );
我知道 new
或 std :: string
复制构造函数可能会抛出,但这不是我的意思。我只是想知道,取消引用 u
是否已经可以引发异常。我觉得奇怪的是, operator *
被 not 标记为 noexcept
而 std :: unique_ptr
方法 get
实际上被标记为 noexcept
。换句话说:
I know that new
or the std::string
copy constructor could throw, but this is not my point here. I was just wondering whether dereferencing u
could already throw an exception. I find it strange that operator*
is not marked noexcept
while the std::unique_ptr
method get
is actually marked noexcept
. In other words:
*( u.get() )
整体上为
,而
*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 *()
可能涉及调用 operator *()
重载,调用您存储在 unique_ptr
中的类型。请注意,存储在 unique_ptr
中的类型不必是裸指针,可以通过嵌套类型 D :: pointer $更改类型。 c $ c>,其中
D
是 unique_ptr
的删除程序的类型。这就是为什么函数不是 noexcept
的原因。
unique_ptr::operator*()
could involve a call to an operator*()
overload for the type you're storing in the unique_ptr
. 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 . This is why the function is not noexcept
.
此警告不适用于您的用例,因为您将 std :: string *
重新存储在 unique_ptr
中,而不是将运算符重载的某些类型*
。因此,通话实际上对您来说是 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*
. So the call is effectively noexcept
for you.
这篇关于“无抛出取消引用”; std :: unique_ptr的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!