编辑:我更改了标题,因为它几乎不适合问题,因为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 异常。但这不是事实,所以我不知道出了什么问题。有什么建议么?