Search code examples
c++qtcopy-constructorassignment-operatorqobject

C++ Assignment Operator without Copy Constructor


The question: Can I define an assignment operator and not the copy constructor? For an internal class (not exposed in the API), is this still a bad design practice?

The reason I need it: As this question mentions, QObject makes its copy constructor and assignment operator private so that if a subclass tries to use either, an error is issued at compile-time.

I need to define an assignment operator however in order to copy the "value" (and not the "identity" as the Qobject documentation describes. I don't use this class's copy constructor anywhere.

The reason I don't want to write a copy constructor is that it will be duplicating code that I won't use anyway.


Solution

  • While possible, as DeadMG says, it is rather foolish.

    You don't have to call the base class's copy constructor from your own, so if you absolutely have to have value semantics, then it is still possible. But in the context of QObjects, this is still rather unorthodox. Even for your own internal classes, the principle of least surprise still needs to be kept in mind.

    If absolutely necessary, I would avoid the traditional copy constructor/assignment operator, and work via member functions. The expected semantics of QObject derivatives will be maintained, but you have a way to explicitely do what you want to have done.

    struct SomeType : QObject {
        QSharedPointer<SomeType> Clone() const;
        //or
        SomeType& CopyValue(const SomeType&);
    
        //rest of implementation
    };