[英]Vector of shared_ptr of an class C++
as the title says I want to declare a vector from shared_ptr of a class.正如标题所说,我想从类的 shared_ptr 声明一个向量。 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.同样从类中,如果您使用迭代器或通过 0 直接访问,则此处对方法的访问不起作用。
RemoteVerbindungen[0]->startUp();
RemoteVerbindungen[VerbindungsNr]->startUp();
the member method "starUp" is not executed.不执行成员方法“starUp”。 The access to "RemoteConnections" Vector is not possible via the iterator.
无法通过迭代器访问“RemoteConnections”向量。 Compiler error type conversion not possible.
无法进行编译器错误类型转换。
Do I create the new ptr under the vector pointing to a newly created object of type "connection"?我是否在指向新创建的“连接”类型对象的向量下创建新的 ptr?
You should prefer std::make_shared()
instead of using new
manually:您应该更喜欢
std::make_shared()
而不是手动使用new
:
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
:
auto VerbindungsNr = RemoteVerbindungen.begin();
Now, that being said, RemoteVerbindungen[0]->startUp();
现在,话虽如此,
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
.如果
vector
不为空,并且索引 0 处的shared_ptr
未设置为nullptr
,则应该可以正常工作。
However, RemoteVerbindungen[VerbindungsNr]->startUp();
然而,
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:你需要解引用迭代器来访问它所引用的
shared_ptr
,然后你可以使用shared_ptr::operator->
来访问connection
对象的成员,例如:
(*VerbindungsNr)->startUp();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.