How do I copy object in Qt?

雨燕双飞 提交于 2019-11-27 02:05:55
NG.

It seems the copy constructor and assignment operator are disabled. From this.

No copy constructor or assignment operator

QObject has neither a copy constructor nor an assignment operator. This is by design. Actually, they are declared, but in a private section with the macro Q_DISABLE_COPY(). In fact, all Qt classes derived from QObject (direct or indirect) use this macro to declare their copy constructor and assignment operator to be private. The reasoning is found in the discussion on Identity vs Value on the Qt Object Model page.

The main consequence is that you should use pointers to QObject (or to your QObject subclass) where you might otherwise be tempted to use your QObject subclass as a value. For example, without a copy constructor, you can't use a subclass of QObject as the value to be stored in one of the container classes. You must store pointers.

Aaron is correct about using the assignment operator.

The only way that I'm aware of to make a copy of an object, if you really have to, is to use Serialization as described in QDataStream Class. This would make a deep copy of the object.

Or have you considered wrapping the class as a QSharedPointer pointer that you can safely pass around. This would be a shadow or reference copy of the object though.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!