首页 > 解决方案 > 如何访问 std::shared_ptr 方法

问题描述

一切都在标题中。我是 C++ 新手,我不确定我是否正确理解了 shared_ptr ......

我有这个方法:

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

我用来获取一组东西:

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

之后我想用它迭代它:

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

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

我的问题是如何访问 i 方法?

我试图通过调试和 cout 来了解我正在使用的东西:

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

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

标签: c++c++11shared-ptr

解决方案


我认为您很困惑,因为arretCourant不是. 它是一个迭代器,引用 的元素,a 。std::shared_ptrstd::setstd::setstd::shared_ptr

因此,为了在std::shared_ptr指向的对象上调用方法,您需要首先取消引用迭代器以获取对的引用std::shared_ptr,然后再次取消引用以获取对std::shared_ptr指向的对象的引用。因此,要调用该对象的方法,请使用:

(*arretCourant)->methodName()

std::shared_ptr重载->运算符以使其调用指向的对象上的方法,而不是其std::shared_ptr本身。它还重载了间接运算符*以返回对其指向的对象的引用,因此

(**arretCourant).methodName()

也有效。

如果你使用arretCourant->methodName()你正在取消引用迭代器,但不是std::shared_ptr,所以你正在调用methodName()std::shared_ptr本身。


推荐阅读