[英]Vector of shared_ptr of an class C++
正如標題所說,我想從類的 shared_ptr 聲明一個向量。 這是班級成員。
類頭的聲明:
std::vector<std::shared_ptr<connection>>RemoteVerbindungen;
在課堂上的用法:
RemoteVerbindungen.push_back(std::shared_ptr<connection>(new connection(SERVICE_SOCKET)));
//Iterator positionieren
std::vector<std::shared_ptr<connection>>::iterator VerbindungsNr = RemoteVerbindungen.begin();
同樣從類中,如果您使用迭代器或通過 0 直接訪問,則此處對方法的訪問不起作用。
RemoteVerbindungen[0]->startUp();
RemoteVerbindungen[VerbindungsNr]->startUp();
不執行成員方法“starUp”。 無法通過迭代器訪問“RemoteConnections”向量。 無法進行編譯器錯誤類型轉換。
我是否在指向新創建的“連接”類型對象的向量下創建新的 ptr?
您應該更喜歡std::make_shared()
而不是手動使用new
:
std::vector<std::shared_ptr<connection>> RemoteVerbindungen;
...
RemoteVerbindungen.push_back(std::make_shared<connection>(SERVICE_SOCKET));
並且,在同一語句中聲明和初始化迭代器時更喜歡auto
:
auto VerbindungsNr = RemoteVerbindungen.begin();
現在,話雖如此, RemoteVerbindungen[0]->startUp();
如果vector
不為空,並且索引 0 處的shared_ptr
未設置為nullptr
,則應該可以正常工作。
然而, RemoteVerbindungen[VerbindungsNr]->startUp();
絕對是錯誤的,因為迭代器不是索引。 你需要解引用迭代器來訪問它所引用的shared_ptr
,然后你可以使用shared_ptr::operator->
來訪問connection
對象的成員,例如:
(*VerbindungsNr)->startUp();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.