[英]How to access std::shared_ptr methods
一切都在標題中。 我是 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
不是std::shared_ptr
。 它是一個std::set
迭代器,指的是std::set
::set 的一個元素,它是一個std::shared_ptr
。
因此,為了調用std::shared_ptr
指向的 object 上的方法,您需要首先取消引用迭代器以獲取對std::shared_ptr
的引用,然后再次取消引用以獲取對std::shared_ptr
::shared_ptr 的 object 的引用std::shared_ptr
指向。 因此,要在 object 上調用方法,請使用:
(*arretCourant)->methodName()
std::shared_ptr
重載->
運算符,使其調用 object 指向的方法,而不是std::shared_ptr
本身。 它還重載了間接運算符*
以返回對它指向的 object 的引用,所以
(**arretCourant).methodName()
也有效。
如果您使用arretCourant->methodName()
您正在取消引用迭代器,而不是std::shared_ptr
,因此您在std::shared_ptr
本身上調用methodName()
。
您可以像原始指針一樣取消引用shared_ptr
例如:
struct A{
void method() {}
};
shared_ptr<A> a = make_shared<A>();
a->method();
如果您需要std::shared_ptr
的方法,則不應取消引用,例如:
auto refCount = a.use_count();
你沒有Arret::Ptr
,你有一個std::set<Arret::Ptr, compArret>::const_iterator
。 您將需要取消引用它以獲取指針(並取消引用它以獲取底層Arret
)
如果你使用 ranged-for,你會得到Arret::Ptr
s,例如
for (auto ptr : arrets)
{
ptr->method();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.