Why cannot a non-member function be used for overloading the assignment operator?

前端 未结 9 2221
南笙
南笙 2020-11-27 18:51

The assignment operator can be overloaded using a member function but not a non-member friend function:

class Test
{
    int a;
public:
    Test         


        
9条回答
  •  青春惊慌失措
    2020-11-27 19:19

    This post applies to C++11

    Why would someone want a non-member operator=? Well, with a member operator= then the following code is possible:

    Test const &ref = ( Test() = something ); 
    

    which creates a dangling reference. A non-member operator would fix this:

    Test& operator=(Test &obj1, Test obj2)
    

    because now the prvalue Test() will fail to bind to obj1. In fact this signature would enforce that we never return a dangling reference (unless we were supplied with one, of course) - the function always returns a "valid" lvalue because it enforces being called with an lvalue.

    However in C++11 there is now a way to specify that a member function can only be called on lvalues, so you could achieve the same goal by writing the member function:

    Test &operator=(Test obj2) &
    //                        ^^^
    

    Now the above code with dangling reference will fail to compile.


    NB. operator= should take the right-hand-side by either value or const reference. Taking by value is useful when implementing the copy and swap idiom, a technique for easily writing safe (but not necessarily the fastest) copy-assignment and move-assignment operators.

提交回复
热议问题