Assigning an Object to a Method Call

I have a class whose name is YourClass. And my problem is that the WHY compiler DOES NOT generate an error for the following code?

YourClass AMethod(){ return YourClass();}
AMethod() = YourClass();

[In this case, IN MY OPINION, AMethod will simply return a value (I mean that it does not matter l).]

EDIT: If I can do it higher, then why can't I do the following

int AMethod(){ return a;}
AMethod() = 5;
+3
source share
4 answers

EDIT1: I think I missed the first question.

The standard says: 3.10 Lvalues ​​and rvalues

The result of calling a function that does not return an Rvalue reference. User-defined function operators and whether such operators calculate or give lvalues ​​by their parameter and return types.

, , . , l. , :

47) , , , , - , lvalues.

, :

AMethod() = YourClass();

AMethod , :

AMethod().operator=(YourClass());

. , l. , ++ , r-!:

5;;; // correct C++ code!

EDIT2:

:

if( &(YourClass() + YourClass()) == &YourClass() )
{
....
}

&(YourClass() + YourClass()) l, . VC, :

warning C4238: nonstandard extension used : class rvalue used as lvalue

, ++, VC !


. -, YourClass AMethod. . , ++ , . , , const YourClass. " ":

const YourClass AMethod(){ return YourClass();}

, . , operator+ , const .

// '+' operator is defined as a friend operator not a member.
friend YourClass operator+(const YourClass& lhs, const YourClass& rhs)
{
...
}

, , :

(a + b) = c;

(a + b) , , , , .

+3

AMethod rvalue. ++ -, -, r- . , .

os.get_disk_accessor(0).wipe(); // wipe() might not be a const member function

rvalues ​​ :

int f();
f() = 5; // won't compile
++f();   // won't either
+2

AMethod()

,

AMethod() = YourClass();

.

0

I think the 1st version is compiled because YourClass has a default constructor, a destructor, a copy constructor, and an assignment operator called AMethod () = YourClass () ;. int AMethod () {return a;} AMethod () = 5; This code does not compile because rvalue does not exist.

0
source

Source: https://habr.com/ru/post/1719053/


All Articles