简体   繁体   中英

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

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.

You can dereference a shared_ptr just like a raw pointer eg:

struct A{
   void method() {}
};
shared_ptr<A> a = make_shared<A>();
a->method();

you should not dereference if you needed a method of std::shared_ptr eg:

auto refCount = a.use_count();

You don't have a Arret::Ptr , you have an std::set<Arret::Ptr, compArret>::const_iterator . You will need to dereference it to get at the pointer (and dereference that to get at the underlying Arret )

You do get Arret::Ptr s if you use a ranged-for, eg

for (auto ptr : arrets)
{
    ptr->method();
}

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