繁体   English   中英

C++类的shared_ptr向量

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM