Search code examples
qtc++11qt5movemove-semantics

Move semantics in Qt without pointers?


I have a Qt project, there I have an Object, which is going to be copied a lot of time. Therefor I would like to add move semantics.

#ifndef OBJECTTOCOPY_H
#define OBJECTTOCOPY_H

#include <QColor>
#include <QString>
#include <QDataStream>
namespace level_1     {
namespace level_2 {
class ObjectToCopy {
public:

  explicit ObjectToCopy(const QString& _name = "", const QColor& colorBody = QColor() );

  // MOVE
  ObjectToCopy(ObjectToCopy && other);  

  static quint32 _valueInt32;
  static quint16 _valueInt16;
  QString _name;
  QColor  _colorBody;

private:
};
}
}
#endif // OBJECTTOCOPY_H

How do I steal the pointers of the member variables, since they are no pointers?

ObjectToCopy::ObjectToCopy (ObjectToCopy&& other)
    : _valueInt32( other._valueInt32  )
    , _valueInt16( other._valueInt16 )
    , _name( other._name )
    , _colorBody( other._colorBody )
{
    other._valueInt32 = 0;
    other._valueInt16 = 0;
    other.name.clear();
    other._colorBody = QColor();    
}
  1. Does that make sense for non-pointers?
  2. Is it ok to reset QString 's like string.clear(); to mark that for the garbage collector?
  3. How could I reset a QColor object?

Solution

  • You are looking for std::move:

    ObjectToCopy::ObjectToCopy (ObjectToCopy&& other)
        : _valueInt32( other._valueInt32  )
        , _valueInt16( other._valueInt16 )
        , _name( std::move(other._name) )
        , _colorBody( std::move(other._colorBody) )
    {
        other._valueInt32 = 0;            //probably not necessary
        other._valueInt16 = 0;            //probably not necessary
        //other.name.clear();             //not necessary
        //other._colorBody = nullptr;     //not necessary
    }
    
    1. It makes sense to move non-pointers. You are in the process of making such an object. Moving integers doesn't help, but doesn't hurt either, so you may as well do it for consistancy. Moving things that don't have a move constructor also works: If no move constructor is available the copy constructor is used (moving is not always better, but not worse either).

      The implementation above says "move by copying the ints and moving the name and the _colorBody".

      Make sure you do not read from variables you moved from.

    2. It is ok, but not necessary. other is supposed to be a temporary that will get destroyed anyways. (C++ does not have a garbage collector in your sense)

      Also once an object is moved from it tends to be in the cleared state like for QString, but that is not always the case.

    3. You cannot really. You can assign a default constructed one like other._colorBody = QColor(); but that just means it sets the color to black. A QColor cannot be empty, it always has some color.

    Also read What are move semantics?