开发者

Compare shared_ptr with object created on stack

开发者 https://www.devze.com 2022-12-20 04:30 出处:网络
I have a situation where I would like to compare an object encapsulated by a shared_ptr with the same type of object开发者_开发百科 created on a stack. Currently, I\'m getting the raw pointer and dere

I have a situation where I would like to compare an object encapsulated by a shared_ptr with the same type of object开发者_开发百科 created on a stack. Currently, I'm getting the raw pointer and dereferencing it to do the comparison eg:

Object A;
std::shared_ptr<Object> B;

// assume class Object has its comparison operators overloaded
if ( *B.get() < A )
    // do stuff here

Is there a better way to do this? That is assuming that when both objects meet to be compared with each other, one is a shared_ptr and the other is not.


shared_ptr overloads operator*() so that it acts just like a pointer, so just write:

if ( *B < A ) {

docs: http://www.boost.org/doc/libs/1_42_0/libs/smart_ptr/shared_ptr.htm#indirection


That looks right to me. It's a pointer. To compare what it points to to something else, you need to dereference it.

0

精彩评论

暂无评论...
验证码 换一张
取 消