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*/ );
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() )
is noexcept
as a whole while
*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
. 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
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With