Does type "operator =" return a return type if I want to make the class not copied?

Suppose I have a class that does not support copying in order, so I don’t want to save a compiler-implemented instance constructor and an assignment operator. I also do not want to implement them, because either

  • it takes extra effort and I don't need these operations in my class or
  • these operations will not make sense in my class

so I want to ban them. To do this, I will declare them private and will not execute the implementation :

class NonCopyable {
private:
   NonCopyable( const NonCopyable& ); //not implemented anywhere
   void operator=( const NonCopyable& ); //not implemented anywhere
};

Now I can choose any return type for the member function operator=(). Will it matter what type of return I choose?

+5
source
5

:

  • void / (a = b = c/f (d = e)) , , ( , , ).

  • void (, , ), :

    • operator=
    • ,
    • / operator=.
  

, , ( , ).

  
  • , operator= - ( ) ....
+1

, .

++ - , . operator=(), " X, X&, const X&, volatile X& const volatile X&". †† , void operator=( const NonCopyable& ); - (, ).

, . NonCopyable , , private.

class Foo : NonCopyable
{
};

int main()
{
    Foo a;
    Foo b;
    // Compiler complains about `operator=(const NonCopyable&)`
    // not accessible or something like that.
    a = b;
}

, , . , , , .


† , , , - . , , , , X& , .

†† ++: 12.8 [class.copy]

9 X::operator= - - - X X, X&, const X&, volatile X& const volatile X&.

+7

, . NonCopyable &, .

+2

, - operator=, .

+1

No, it doesn’t matter since you never follow the instructions return. If you try to call the operator, the compiler will not be able to find the implementation (with any type return, so the return type does not matter).

Interestingly, the boost::noncopyablecopy assignment operator is declared to return a const noncopyable&, but I assume this is just a convention.

+1
source

All Articles