Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"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:

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?

like image 305
sperber Avatar asked Aug 21 '14 20:08

sperber


1 Answers

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.

like image 155
Praetorian Avatar answered Sep 23 '22 14:09

Praetorian