don-prog don-prog - 2 months ago 46
C++ Question

How to avoid objects copying during passing from C++ to QML and again to C++?

I try to load QImage from C++ to QML. So I already created subclass of QQuickPaintedItem in which I load my QImage(casted to QVariant) using slot(that means that I use QML in this case only as transfer). But I have only one issue: I pass the QImage by value, and I know that I can't pass arguments from QML to C++ using references and pointers.

So, whether there is a some trick which allows to avoid objects copying during passing from C++ to QML and again to C++?

Answer

The "trick" is built in to Qt: Like many other classes which contain data, QImage uses implicit data sharing AKA copy-on-write/CoW, quote from Qt5 docs:

QImage objects can be passed around by value since the QImage class uses implicit data sharing.

Link in the docs provides more details about what this means in context of Qt, but in short actual QImage instance is very small and cheap to pass around as value. It is basically just a pointer to shared data with reference count. When an instance is modified, it is detached (deep copy taken) first if reference count is greater than 1, but when not modifying, it's just copying around a pointer.