【问题标题】:Vector of shared_ptr of an class C++类 C++ 的 shared_ptr 向量
【发布时间】:2020-11-08 19:37:48
【问题描述】:

正如标题所说,我想从一个类的 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”向量。无法进行编译器错误类型转换。

我是否在指向新创建的“connection”类型对象的向量下创建新的ptr?

【问题讨论】:

  • 您告诉我们,您甚至不清楚“不起作用”是什么意思。请提供minimal reproducible example 并澄清问题
  • 我希望问题或问题得到更好的表述
  • 嗯,第二部分是因为你使用了错误的迭代器。迭代器不是索引,它更像是指向元素的指针。第一个问题仍然不清楚,因为您没有提供minimal reproducible example 或显示您期望发生的事情(以及您如何确定未调用该函数)

标签: c++ oop vector smart-pointers


【解决方案1】:

您应该更喜欢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]-&gt;startUp(); 应该可以正常工作,如果 vector 不为空,并且索引 0 处的 shared_ptr 未设置为 nullptr

但是,RemoteVerbindungen[VerbindungsNr]-&gt;startUp(); 肯定是错误的,因为迭代器不是索引。你需要解引用迭代器才能访问它所引用的shared_ptr,然后你可以使用shared_ptr::operator-&gt;来访问connection对象的成员,例如:

(*VerbindungsNr)->startUp();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-15
    • 1970-01-01
    • 1970-01-01
    • 2014-09-08
    • 2017-01-18
    • 2018-07-16
    相关资源
    最近更新 更多