gpt4 book ai didi

c++ - 如何正确传递指针

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:30:08 26 4
gpt4 key购买 nike

编辑:我更改了标题,因为它几乎不适合问题,因为 new 运算符不是问题所在。 以前的标题是“Operator new 会失败吗?”

在下面的代码中,在客户端连接到服务器之前,我创建了一个新的 Socket 对象指针。当客户端连接时,我使用 new 创建对象。但是不知何故,当我使用调试器(Eclipse CDT、g++ Ubuntu/Linaro 4.6.3-1ubuntu5)逐步执行代码时,我看到在调用 new 运算符后,指针仍然为 NULL。

class Socket
{
public:
Socket( int domain, int type, int protocol = 0 );
~Socket();
[...]
int accept( Socket * socket );
[...]
private:
Socket();
int mSocketDescriptor;
int mNetworkProtocol;
int mTransportProtocol;
};

[...]

int Socket::accept( Socket * socket )
{
// Accept one connection (blocking)
struct sockaddr_in cli_addr;
socklen_t clilen = sizeof(cli_addr);
int ret = ::accept(mSocketDescriptor, (struct sockaddr *) &cli_addr, &clilen);
if ( ret >= 0 ){
socket = new Socket(); // <- Here's the problem, socket remains NULL
socket->mSocketDescriptor = ret;
socket->mNetworkProtocol = this->mNetworkProtocol;
socket->mTransportProtocol = this->mTransportProtocol;
}
return ret;
}

主循环:

// Accept all incoming connections in a loop
while(true){

// Accept one connection (blocking)
net::Socket * newConn = NULL;
if (socket.accept(newConn) < 0){
perror("accept()");
exit(EXIT_FAILURE);}

// Create a new thread that is talking to the client
pthread_t nThreadID;
pthread_create(&nThreadID, NULL, ClientMainThreadProc, newConn);
}

我通读了 C++ 引用资料。它告诉我,如果 new 失败,应该引发 bad_alloc 异常。但这不是事实,所以我不知道出了什么问题。有什么建议吗?

最佳答案

好的,正如hmjd所述,问题的解决方案是:

I think you mean newConn is still NULL in the caller? If so, pass the pointer by reference as a copy of the pointer is being passed to accept() so any change is local to the accept() function.

不幸的是,我的调试器将我引向了错误的方向,显示套接字指针注释甚至在本地发生了变化。但是当通过引用传递指针时一切正常。

关于c++ - 如何正确传递指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13341565/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com