Home > OS >  Define operator! for shared_ptr<A>
Define operator! for shared_ptr<A>

Time:12-12

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.

CodePudding user response:

Try this

shared_ptr b; 
bool result = !*b; 

CodePudding user response:

You cannot do that. You need to dereference the pointer first.

bool result = b and !(*b);

CodePudding user response:

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);
  • Related