开发者

C++ Assignment Operator without Copy Constructor

开发者 https://www.devze.com 2023-03-22 06:10 出处:网络
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 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 th开发者_StackOverflow社区at 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.


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.


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
};
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号