简体   繁体   中英

Vector of shared_ptr of an class C++

as the title says I want to declare a vector from shared_ptr of a class. This is class member.

Deklaration of class header:

std::vector<std::shared_ptr<connection>>RemoteVerbindungen;

usage in the class:

  RemoteVerbindungen.push_back(std::shared_ptr<connection>(new connection(SERVICE_SOCKET)));      
  //Iterator positionieren
  std::vector<std::shared_ptr<connection>>::iterator VerbindungsNr = RemoteVerbindungen.begin();

Also from the class, here the access to the method does not work, if you use the iterator or the direct access via 0.

RemoteVerbindungen[0]->startUp();
RemoteVerbindungen[VerbindungsNr]->startUp();

the member method "starUp" is not executed. The access to "RemoteConnections" Vector is not possible via the iterator. Compiler error type conversion not possible.

Do I create the new ptr under the vector pointing to a newly created object of type "connection"?

You should prefer std::make_shared() instead of using new manually:

std::vector<std::shared_ptr<connection>> RemoteVerbindungen;
...
RemoteVerbindungen.push_back(std::make_shared<connection>(SERVICE_SOCKET));

And, prefer auto when declaring and initializing the iterator in the same statement:

auto VerbindungsNr = RemoteVerbindungen.begin();

Now, that being said, RemoteVerbindungen[0]->startUp(); should work just fine, if the vector is not empty, and the shared_ptr at index 0 is not set to nullptr .

However, RemoteVerbindungen[VerbindungsNr]->startUp(); is definitely wrong, as an iterator is not an index. You need to dereference the iterator to access the shared_ptr that it refers to, and then you can use shared_ptr::operator-> to access the members of the connection object, eg:

(*VerbindungsNr)->startUp();

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