Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does signature of custom assignment operator=() matter when I just want to disable it?

I need to disable the copy assignment operator. This will work:

A& operator=(const A&);

Will it work if I don't specify exact parameters for operator=?
I mean something like this:

void operator=(void);

The returning value is right, I can write whatever I want, but what about the parameter type?
Will this override the default operator= for class?

like image 495
user1289 Avatar asked May 29 '16 08:05

user1289


2 Answers

From 12.8p17 of the C++ standard draft:

A user-declared copy assignment operator X::operator= is a non-static non-template member function of class X with exactly one parameter of type X, X&, const X&, volatile X& or const volatile X&.

I guess this replies better than any other test or sample code.

Note that something similar applies also to the move assignment operator, see 12.8p19:

A user-declared move assignment operator X::operator= is a non-static non-template member function of class X with exactly one parameter of type X&&, const X&&, volatile X&&, or const volatile X&&.

These also confirm that, as you guessed, return value types don't matter.

like image 155
skypjack Avatar answered Nov 04 '22 12:11

skypjack


There can be different kinds of assignments. Only copy assignment and move assignment are potentially generated by the compiler. They are generated if there is no copy/move assignment. So, if you want to disable copy and/or move assignment the argument type does matter although there is some flexibility as copy assignment can different argument types. The return type doesn't matter, though.

class A {
public:
    void operator=() = delete; // not legal: assignment takes exactly one argument
    void operator=(A) = delete; // OK: copy assignment disabled
    void operator=(A&) = delete; // OK: copy assignment disabled
    void operator=(A const&) = delete; // OK: copy assignment disabled
    void operator=(A&&) = delete; // OK: move assignment disabled
};

There are also variations replacing const by volatile or const volatile qualifying as copy/move assignments. When you disable a copy assignment, automatic generation of move assignment will be disabled, too. If you disable move assignment, I think copy assignment would still be generated. If you disable anything which cannot be a copy or move assignment, copy/move assignment are still generated.

like image 24
Dietmar Kühl Avatar answered Nov 04 '22 14:11

Dietmar Kühl