Qt中QObject子类Comunication临时对象存入QVector报错如何解决
问题根因
Qt中所有继承自QObject的类都会默认禁用拷贝构造函数和拷贝赋值运算符,你的Comunication类继承了QObject,所以不能按值传递对象,这是报错的直接原因。
另外你定义的存储容器是QVector<Comunication *>,存储的是对象指针,你之前创建栈上临时对象的逻辑也不符合存储要求,栈对象在循环结束后会自动析构,即使强转存指针也会变成悬空指针。
具体修改步骤
1. 修改addPort方法的参数类型
把原来按值传参的定义改为传指针:
首先修改ControlCommunication.h:
// 替换原来的void addPort(Comunication com); void addPort(Comunication* com);
然后修改ControlCommunication.cpp中对应的addPort实现:
void ControlCommunication::addPort(Comunication* com) { comunicationports.append(com); }
2. 修改checkPorts中对象创建逻辑
不要创建栈上的临时对象,改为在堆上创建对象返回指针:
void ControlCommunication::checkPorts(){ qint16 vendorid = cuquito.getVendorID(); qint16 productid = cuquito.getProductID(); const QString blankString = "N/A"; for (const QSerialPortInfo &serialPortInfo : QSerialPortInfo::availablePorts()) { // 堆上创建Comunication对象 Comunication *com = new Comunication(serialPortInfo.portName()); // 可选:给com设置父对象,让ControlCommunication析构时自动回收内存 com->setParent(this); addPort(com); } }
3. 可选优化:对齐Qt构造函数规范
可以给Comunication的构造函数加上父对象参数,符合Qt开发习惯,修改Comunication.h:
// 替换原来的构造函数声明 explicit Comunication(QString serialPortName, QObject *parent = nullptr);
对应的Comunication.cpp构造函数实现同步修改:
Comunication::Comunication(QString serialPortName, QObject *parent) : QObject(parent), portname(std::move(serialPortName)) { // 保留原有构造逻辑 }
修改后创建对象可以直接传父对象:Comunication *com = new Comunication(serialPortInfo.portName(), this);
内存注意事项
如果没有给Comunication对象设置父对象,需要在ControlCommunication的析构函数中手动遍历comunicationports容器,delete所有指针避免内存泄漏。
内容的提问来源于stack exchange,提问作者luarpy
相关产品推荐
相关产品推荐

