class C++ 的 shared_ptr 向量
Vector of shared_ptr of an class C++
正如标题所说,我想从 class 的 shared_ptr 声明一个向量。
这是 class 成员。
classheader声明:
std::vector<std::shared_ptr<connection>>RemoteVerbindungen;
class中的用法:
RemoteVerbindungen.push_back(std::shared_ptr<connection>(new connection(SERVICE_SOCKET)));
//Iterator positionieren
std::vector<std::shared_ptr<connection>>::iterator VerbindungsNr = RemoteVerbindungen.begin();
同样来自class,如果您使用迭代器或通过0直接访问,这里访问该方法不起作用。
RemoteVerbindungen[0]->startUp();
RemoteVerbindungen[VerbindungsNr]->startUp();
成员方法“starUp”没有被执行。
无法通过迭代器访问“RemoteConnections”向量。无法进行编译器错误类型转换。
我是否在指向新创建的 object 类型“连接”的向量下创建新的 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();
现在,话虽如此,如果 vector
不为空,并且索引 0 处的 shared_ptr
未设置为 [=19=,则 RemoteVerbindungen[0]->startUp();
应该可以正常工作].
然而,RemoteVerbindungen[VerbindungsNr]->startUp();
肯定是错误的,因为迭代器不是索引。您需要取消引用迭代器以访问它所引用的 shared_ptr
,然后您可以使用 shared_ptr::operator->
访问 connection
对象的成员,例如:
(*VerbindungsNr)->startUp();
正如标题所说,我想从 class 的 shared_ptr 声明一个向量。 这是 class 成员。
classheader声明:
std::vector<std::shared_ptr<connection>>RemoteVerbindungen;
class中的用法:
RemoteVerbindungen.push_back(std::shared_ptr<connection>(new connection(SERVICE_SOCKET)));
//Iterator positionieren
std::vector<std::shared_ptr<connection>>::iterator VerbindungsNr = RemoteVerbindungen.begin();
同样来自class,如果您使用迭代器或通过0直接访问,这里访问该方法不起作用。
RemoteVerbindungen[0]->startUp();
RemoteVerbindungen[VerbindungsNr]->startUp();
成员方法“starUp”没有被执行。 无法通过迭代器访问“RemoteConnections”向量。无法进行编译器错误类型转换。
我是否在指向新创建的 object 类型“连接”的向量下创建新的 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();
现在,话虽如此,如果 vector
不为空,并且索引 0 处的 shared_ptr
未设置为 [=19=,则 RemoteVerbindungen[0]->startUp();
应该可以正常工作].
然而,RemoteVerbindungen[VerbindungsNr]->startUp();
肯定是错误的,因为迭代器不是索引。您需要取消引用迭代器以访问它所引用的 shared_ptr
,然后您可以使用 shared_ptr::operator->
访问 connection
对象的成员,例如:
(*VerbindungsNr)->startUp();