编译时qvariant.h出现deprecated-copy警告问题咨询
QVariant编译警告问题解答
问题描述
编译程序时触发多个QVariant相关的编译警告,未修改Qt库及源代码,编译日志如下:
/Qt/5.9.9/gcc_64/mkspecs/linux-g++ -o tl_ansi_codes.o /mydir/tl_ansi_formatting/tl_ansi_codes.cpp In file included from /opt/Qt/5.9.9/gcc_64/include/QtCore/qlocale.h:43, from /opt/Qt/5.9.9/gcc_64/include/QtCore/qtextstream.h:46, from /opt/Qt/5.9.9/gcc_64/include/QtCore/qdebug.h:49, from /opt/Qt/5.9.9/gcc_64/include/QtCore/QDebug:1, from /mydir/tl_ansi_formatting/tl_ansi_codes.cpp:9: /opt/Qt/5.9.9/gcc_64/include/QtCore/qvariant.h: In constructor ‘QVariant::QVariant(QVariant&&)’: /opt/Qt/5.9.9/gcc_64/include/QtCore/qvariant.h:265:25: warning: implicitly-declared ‘constexpr QVariant::Private& QVariant::Private::operator=(const QVariant::Private&)’ is deprecated [-Wdeprecated-copy] 265 | { other.d = Private(); } | ^ /opt/Qt/5.9.9/gcc_64/include/QtCore/qvariant.h:380:16: note: because ‘QVariant::Private’ has user-provided ‘QVariant::Private::Private(const QVariant::Private&)’ 380 | inline Private(const Private &other) Q_DECL_NOTHROW | ^~~~~~~ g++ -c -pipe -g -Wall -W -D_REENTRANT -fPIC -DQT_DEPRECATED_WARNINGS -Dproject_vls=1 -DQT_GUI_LIB -DQT_NETWORK_LIB -DQT_SQL_LIB -DQT_CORE_LIB -I/mydir//project -I. - /opt/Qt/5.9.9/gcc_64/include/QtCore/qvariant.h: In constructor ‘QVariant::QVariant(QVariant&&)’: /opt/Qt/5.9.9/gcc_64/include/QtCore/qvariant.h:265:25: warning: implicitly-declared ‘constexpr QVariant::Private& QVariant::Private::operator=(const QVariant::Private&)’ is deprecated [-Wdeprecated-copy] 265 | { other.d = Private(); }
警告含义
这个-Wdeprecated-copy是gcc 9及以上版本新增的警告,核心逻辑如下:
QVariant::Private类自定义了拷贝构造函数,但没有显式定义拷贝赋值运算符- 根据C++规则,编译器会自动为它生成一个隐式的拷贝赋值运算符
- 新版gcc认为这种“有自定义拷贝构造但隐式生成赋值运算符”的写法存在一致性风险,因此将该隐式运算符标记为废弃,触发警告
- 警告触发点在
QVariant的移动构造函数中:other.d = Private();这行代码调用了这个隐式生成的拷贝赋值运算符
出现原因
你没修改Qt代码,但触发警告的本质是版本兼容性问题:
- Qt 5.9.9是较老的版本,发布时gcc还未引入
-Wdeprecated-copy警告 - 你当前使用的gcc版本(9+)默认开启了这个警告,且编译参数里的
-Wall -W会启用所有基础警告 - Qt老版本的
QVariant::Private实现刚好符合触发该警告的条件,因此编译时会弹出提示
解决方案
- 屏蔽特定警告:在编译参数中添加
-Wno-deprecated-copy,单独关闭这个警告,不影响其他警告输出 - 升级Qt版本:升级到Qt 5.15或更高版本,这些版本已经修复了该兼容性问题,适配了新版gcc的警告规则
- 忽略警告:该警告仅为编译器提示,不会影响程序的编译和运行,若能接受警告输出,可直接忽略
内容的提问来源于stack exchange,提问作者TSG
相关产品推荐
相关产品推荐

