简体   繁体   中英

Why doesn't std::weak_ptr<> provide a bool conversion?

C++11's std::shared_ptr<> provides a kind of bool operator.

operator unspecified-bool-type() const;

(It's not a straight-up operator bool() const due to the dangers from implicit casting of type bool .)

Why doesn't std::weak_ptr<> have a similar operator? I find myself constantly typing

if( !wp.expired() )

when I want to type

if( wp )

Why no bool conversion for weak_ptr?

if(!wp.expired()) is almost always a wrong check in multithreaded code, because directly after that if statement the pointer could expire. As such, if weak_ptr had exactly that as the semantics for the bool conversion, it would never be used anyways.

If you want to check if the pointer is alive, use lock and check the obtained shared_ptr .

If you want to know if the pointer is dead, use expired .

As you can see, it just doesn't make sense to provide a boolean conversion. For shared_ptr , it totally does. Btw, the conversion operator is explicit operator bool() const noexcept; in C++11.

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