Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 580
Alan Turing Avatar asked Mar 12 '26 11:03

Alan Turing


1 Answers

There's nothing stopping you. It is, however, a pretty dumb idea.

T t = GetSomeT();

versus

T t;
t = GetSomeT();

Pretty trivial to transform the first into the second, but you're just wasting my time, both dev and processor, making me do it. If it's not default-constructible, I guess that it would be harder... but I'm still not seeing the point. The copy constructor can be defined by the compiler if it's trivial, or you can even define it in terms of the assignment operator if you want DRY.

class T {
    T(const T& ref) {
         *this = ref;
    }
};

Not having a copy constructor will also inhibit your ability to copy-and-swap, the usual idiom for implementing assignment operators.

like image 187
Puppy Avatar answered Mar 14 '26 01:03

Puppy