Search code examples
c++c++11shared-ptr

How to comprehend "std::relational operators (shared_ptr) compares directly the stored pointers"


As per the documentation(http://www.cplusplus.com/reference/memory/shared_ptr/operators/), which says: [emphasis mine]

The comparison compares directly the stored pointers (i.e., the value the objects dereference to, and not their owned pointer (i.e., the managed objects that are deleted on destruction), which may not be the same in alias shared_ptr objects (alias-constructed objects and their copies).

I can understand the example code in the documentation aforedmentioned to some degree.But I could not comprehend the quotes above.

Could somebody make it clear by giving some simple examlples and explain when using this operator makes sense?

I have been confused for a long time. I would be very grateful to have some help with this question.

Here is the example code which i can understand to some degree:

// shared_ptr relational operators
#include <iostream>
#include <memory>

int main () {
  std::shared_ptr<int> a,b,c,d;

  a = std::make_shared<int> (10);
  b = std::make_shared<int> (10);
  c = b;

  std::cout << "comparisons:\n" << std::boolalpha;

  std::cout << "a == b: " << (a==b) << '\n';
  std::cout << "b == c: " << (b==c) << '\n';
  std::cout << "c == d: " << (c==d) << '\n';

  std::cout << "a != nullptr: " << (a!=nullptr) << '\n';
  std::cout << "b != nullptr: " << (b!=nullptr) << '\n';
  std::cout << "c != nullptr: " << (c!=nullptr) << '\n';
  std::cout << "d != nullptr: " << (d!=nullptr) << '\n';

  return 0;
}

Solution

  • Let's say, you have this struct:

    struct Foo { int a, b; };
    

    Then you can generate aliased shared pointers like this:

    void f()
    {
        // create
        shared_ptr<Foo> orig(new Foo{1, 2});
        // aliased pointer 1, points into object held by orig
        shared_ptr<int> pa(orig, &orig->a);
        // aliased pointer 2, ditto
        shared_ptr<int> pb(orig, &orig->b);
    
        assert(pa != pb);    // passes
    }
    

    Even though pa and pb share ownership of the same object (which they happen to share with orig as well), they carry different pointers, just like you would expect.