c++ - 如何访问 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
解决方案
我认为您很困惑,因为arretCourant
不是. 它是一个迭代器,引用 的元素,即a 。std::shared_ptr
std::set
std::set
std::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
本身。
推荐阅读
- javascript - 在这个例子中,如何使用 JaveScript 来模仿自定义过滤器/选择器?
- talend - tFTPConnection 从上下文设置密码不起作用
- php - 来自键名的多维数组层次结构
- python - 另一个 if 语句中带有比较运算符的 if 语句未运行
- reactjs - 如何在标签处于活动状态时更改标签的侧边框颜色
- html - 跳过链接切断整个网站的标题顶部
- jupyter-lab - jupyter-lab 中的“为输出创建新视图”不适用于全息视图
- linux - 使用 QML 调试标志点安装 PyQt5
- xml - 需要帮助 XSLT 2.0
- scala - 使用 scalapb 为地图编写 TypeMapper