Are all temporaries rvalues in C++?

前端 未结 7 921
隐瞒了意图╮
隐瞒了意图╮ 2020-12-05 04:56

I have been coding in C++ for past few years. But there is one question that I have not been able to figure out. I want to ask, are all temporaries in C++, rvalues?

7条回答
  •  星月不相逢
    2020-12-05 05:27

    Short answer: yes, but I'm not going to quote the standard, because proving the point would require addressing every kind of temporary there is. By definition a temporary has a lifetime of one statement, so assigning things to one would be poor style at best.

    Interesting answer: Copy elision can make (often makes) a temporary object identical with an lvalue object. For example,

    MyClass blah = MyClass( 3 ); // temporary likely to be optimized out
    

    or

    return MyClass( 3 ); // likely to directly initialize object in caller's frame
    

    Edit: as for the question of whether there is any temporary object in those cases, §12.8/15 mentions

    the copy operation can be omitted by constructing the temporary object directly into the target of the omitted copy

    which would indicate that there is a temporary object which may be identical with an lvalue.

提交回复
热议问题