“No-throw dereferencing” of std::unique_ptr

守給你的承諾、 提交于 2019-12-19 17:41:44

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/25434950/no-throw-dereferencing-of-stdunique-ptr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!