简体   繁体   中英

Define operator! for shared_ptr<A>

I have a problem with defining operator ! for my class. I use shared_ptr<A> objects and I would like to use ! on them.

shared_ptr<a> b;
bool result = !b; // using my operator, not !shared_ptr

I tried few times but I'm getting ambiguous error.

Try this

shared_ptr b; 
bool result = !*b; 

shared_ptr doesn't have an operator! defined, but you can compare the pointer it is holding, eg:

shared_ptr<a> b;
bool result = !b.get();

Alternatively, it does have an operator bool defined:

shared_ptr<a> b;
bool result = !(bool)b; // or: !static_cast<bool>(b)

Alternatively, it also has operator== defined for nullptr :

shared_ptr<a> b;
bool result = (b == nullptr);

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