Home > Blockchain >  Does the return type of a deleted operator matter if the operator is deleted?
Does the return type of a deleted operator matter if the operator is deleted?

Time:04-21

I am reading ‘C concurrency in action’, one page talks about copy-assignment operator =delete.

I have googled about it (Deleting copy constructors and copy assignment operators. Which of them are essential?) and tried some code by myself.

I want to know if there is a difference between

void operator= (const MyClass&) = delete;

and

MyClass& operator= (const MyClass&) = delete;

or I can just do

void operator= (MyClass) = delete;

It seems like it will "delete" the operator = anyway...


I just checked cppreference.com about Copy constructors and Copy assignment operator (https://en.cppreference.com/w/cpp/language/copy_constructor)(https://en.cppreference.com/w/cpp/language/copy_assignment).

Could I just use the following code?

   MyClass(MyClass&)=delete;

   void operator= (MyClass) = delete;

I think it will "delete" everything anyway, so I don't need to worry about the "performance" of the copying, right?...

CodePudding user response:

C allows you to have operators with whatever return type you want.
In all cases, you are overloading operator= with different semantics so they will all work.
But it's best to follow the widespread convention of returning a class reference so that assignment chains (a = b = c) and constructs such as (while ((a = b) == c) {...) can work as well.

The second way you wrote:

MyClass& operator=(const MyClass&) = delete;

is most used and as written, there is no need for a named parameter.

  • Related