Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
340 views
in Technique[技术] by (71.8m points)

c++ - Assigning Rvalue returned from function to another Rvalue

class Test {

public:

    int n1;

};

Test func() {

    return Test();

}

int main() {

    func() = Test();

}

This doesn't make sense to me. How and why is this allowed? Is it undefined behavior? If a function returns an rvalue, then how is it possible to set an rvalue to another rvalue? If I tried this with any primitive types, it would give me an error like I expect.

I know that lvalues are a place in memory, so is the function creating a temporary lvalue (rvalue?) and assigning it to another lvalue? Can someone explain how this syntax works?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The value category of the function call expression is in fact an rvalue.

Indeed, you may not call the copy assignment operator on rvalue primitives. The historical definition of rvalues in C was in fact the distinction that they may not be on the left side of an assigment.

The assignment operators of classes are a bit different, though. They're regular member functions. And no rule prevents calling member functions of rvalues. Indeed, it's often quite useful when the functions have side-effects.

How it works, well, the copy assignment operator is called on the temporary, the operator copies the right hand argument, changing the state of the temporary. After the statement, the temporary object is discarded. There is no UB, just pointless copying.

You can prevent calling copy assignment on an rvalue, by declaring the operator with a reference qualifier like this: Test& operator=(Test) & = default;. Ref-qualifiers were added only later in c++11, so (implicit) copy assignment couldn't have been specified to be ref-qualified earlier. Presumably, C++11 didn't change the qualifier of implicit copy constructor to prevent breaking old code that does assign to an rvalue, even though such assignment does seem quite pointless. The High Integrity C++ Coding Standard recommends that you do use ref qualifier with user defined copy assignment operators.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...