Temporary objects - when are they created, how do you recognise them in code?

前端 未结 4 713
醉梦人生
醉梦人生 2020-11-28 01:55

In Eckel, Vol 1, pg:367

//: C08:ConstReturnValues.cpp
// Constant return by value
// Result cannot be used as an lvalue
class X {
   int i;
public:
   X(int          


        
4条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-28 02:53

    1. This is indeed a constructor call, an expression evaluating to a temporary object of type X. Expressions of the form X([...]) with X being the name of a type are constructor calls that create temporary objects of type X (though I don't know how to explain that in proper standardese, and there are special cases where the parser can behave differently). This is the same construct you use in your f5 and f6 functions, just omitting the optional ii argument.

    2. The temporary created by X(1) lives (doesn't get destructed/invalid) until the end of the full expression containing it, which usually means (like in this case with the assignment expression) until the semicolon. Likewise does f5 create a temporary X and return it to the call site (inside main), thus copying it. So in main the f5 call also returns a temporary X. This temporary X is then assigned the temporary X created by X(1). After that is done (and the semicolon reached, if you want), both temporaries get destroyed. This assignment works because those functions return ordinary non-constant objects, no matter if they are just temprorary and destroyed after the expression is fully evaluated (thus making the assignment more or less senseless, even though perfectly valid).

      It doesn't work with f6 since that returns a const X onto which you cannot assign. Likewise does f7(f5()) not work, since f5 creates a temporary and temporary objects don't bind to non-const lvalue references X& (C++11 introduced rvalue references X&& for this purpose, but that's a different story). It would work if f7 took a const reference const X&, as constant lvalue references bind to temporaries (but then f7 itself wouldn't work anymore, of course).

提交回复
热议问题