简体   繁体   中英

“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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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