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

How to access std::shared_ptr methods


everything is in the title. Im new in C++ and im not sure that I undertand shared_ptr properly...

I've this method:

const std::set<Something::Ptr, b> & getSome() const;

that I use to get a set of somethings :

auto s = u->second.getSome();

After that i want to iterate on it with :

for(auto i = s.begin();i != s; s.end();i++)

//(so i=  std::shared_ptr<Something> referring to the first element in s )

My question is how can i access i methods?

I tried to understand what I was working with by debugging and cout some things :

auto whatIsThat1 = *i;
cout << "hello" << whatIsThat1; //>> hello0x13fd500

auto whatIsThat2 = i->get();
cout << "hello" << whatIsThat2; >> hello0x21c2500

Solution

  • I think you are confused because arretCourant is not a std::shared_ptr. It is a std::set iterator referring to an element of the std::set, which is a std::shared_ptr.

    So in order to call a method on the object that the std::shared_ptr points to, you need to first dereference the iterator to get a reference to the std::shared_ptr and then dereference again to get a reference to the object that the std::shared_ptr is pointing to. So to call a method on that object use:

    (*arretCourant)->methodName()
    

    std::shared_ptr overloads the -> operator to make it call the method on the object pointed to, rather than the std::shared_ptr itself. It also overloads the indirection operator * to return a reference to the object it is pointing to, so

    (**arretCourant).methodName()
    

    also works.

    If you use arretCourant->methodName() you are dereferencing the iterator, but not the std::shared_ptr, so you are calling methodName() on the std::shared_ptr itself.