C++中的迭代器不是指针的一种吗?

2023-12-03

好吧,这次我决定使用STL 来制作一个列表。我需要为每个客户端创建一个专用的 TCP 套接字。因此,每当我建立连接时,我都会实例化一个套接字并在列表中添加一个指向它的指针。

list<MyTcp*> SocketList;  //This is the list of pointers to sockets
list<MyTcp*>::iterator it;  //An iterator to the list of pointers to TCP sockets.

将新指针放入套接字很容易,但现在每次连接结束时,我都应该断开套接字并删除指针,这样我就不会出现巨大的内存泄漏,对吗?好吧..我认为我通过设置这个做得很好:

it=SocketList.begin();
while( it != SocketList.end() ){
    if((*it)->getClientId() == id){
    pSocket = it; //    <-------------- compiler complains at this line
    SocketList.remove(pSocket);
    pSocket->Disconnect();
    delete pSocket;
    break;
    }
}

但编译器是这样说的:

 error: invalid cast from type ‘std::_List_iterator<MyTcp*>’ to type ‘MyTcp*’

有人可以帮我吗?我认为我做的事情是正确的,难道迭代器在任何给定时间都只指向集合的元素之一吗?我该如何修复它?


尝试这个:

pSocket = *it; 

迭代器的行为很像指针,但实际上它们可以是指针,也可以是行为类似指针的成熟类。在这种情况下,重要的是,当您取消引用一个容器时,您将获得容器中存储的任何项目。既然你正在存储MyTcp*s 在列表中,当您取消引用迭代器时,您会得到一个MyTcp*. pSocket属于类型MyTcp*所以上面的赋值就成功了。您尝试执行的分配并不是取消对迭代器的引用 - 您正在尝试将迭代器本身分配给pSocket.

这有点像下面的例子:

void foo()
{
    MyTcp *array[10]; // An array full of MyTcp pointers
    MyTcp **iterator = NULL; // pointers make good iterators for arrays (but not for std::lists)
    for (iterator = array; iterator != array + 10; ++iterator)
    {
        // This fails to compile (cannot assign MyTcp** to MyTcp*:
        MyTcp *wrong = iterator;            

        // This succeeds:
        MyTcp *current = *iterator; // important to dereference the iterator
    }
} 
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

C++中的迭代器不是指针的一种吗? 的相关文章

随机推荐