类中的C ++ Qt extern变量,崩溃错误(SIGSEGV)

时间:2014-02-18 18:51:23

标签: c++ qt crash extern sigsegv

我之前从未使用过extern变量而且我在OOP上并不是那么擅长,所以我可能会做一些愚蠢的事情,但这可能是一个线程“碰撞”问题或者别的什么。

在服务器类中,我有一个playerData对象指针,playerDataManager,它在服务器构造函数中初始化。在packetReader头文件中,我将playerDataManager添加为类外的外部变量。当客户端连接到服务器时,packetReader类调用playerData类中的一个函数,该服务器应该将客户端的QTcpSocket *添加到'clients'的QList中,但是它崩溃了。如果我将clients.append(new QTcpSocket());放在playerData构造函数中,它可以正常工作。知道它崩溃的原因吗?

playerdata.h

#ifndef PLAYERDATA_H
#define PLAYERDATA_H

//includes

class playerData
{
public:
    playerData();
    void addPlayer(QTcpSocket* client, QByteArray username);
    QList<QTcpSocket*> clients;

private:
    QMap<QTcpSocket*, QByteArray> usernames;

};

#endif // PLAYERDATA_H

playerdata.cpp

#include "playerdata.h"

playerData::playerData()
{
    //if I put "clients.append(new QTcpSocket());" here, it works fine
}

void playerData::addPlayer(QTcpSocket *client, QByteArray username){
    clients.append(client); //crashes here
    usernames.insert(client, username);
}

packetreader.h

#ifndef PACKET_H
#define PACKET_H

//includes

extern playerData *playerDataManager;

class packetReader
{
public:
    packetReader();
    void processPacket(QByteArray id, QByteArray msg, QTcpSocket *client);

private:
    void processPacket_initialConnection(QByteArray msg, QTcpSocket *client);
    void processPacket_badPacket(QByteArray msg, QTcpSocket *client);

    playerData *playerDataManager;

};

#endif // PACKET_H

packetreader.cpp

#include "packetreader.h"

packetReader::packetReader()
{
}

void packetReader::processPacket(QByteArray id, QByteArray msg, QTcpSocket *client){
    if(id=="0003") processPacket_initialConnection(msg, client);
    else processPacket_badPacket(msg, client);
}

void packetReader::processPacket_initialConnection(QByteArray msg, QTcpSocket *client){
    playerDataManager->addPlayer(client, msg);
}

void packetReader::processPacket_badPacket(QByteArray msg, QTcpSocket *client){
    qDebug()<<"Bad packet"<<msg<<"received from"<<playerDataManager->getUsername(client);
}

server.h和server.cpp只需设置一个基本的tcp服务器,当新客户端连接时,该服务器调用id =“0003”的processPacket函数。

0 个答案:

没有答案