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


in eckel, vol 1, pg:367

//: c08:constreturnvalues.cpp // constant return value // result cannot used lvalue class x {    int i; public:    x(int ii = 0);    void modify(); };  x::x(int ii) { = ii; }  void x::modify() { i++; }  x f5() {    return x(); }  const x f6() {    return x(); }  void f7(x& x) { // pass non-const reference    x.modify(); }  int main() {    f5() = x(1); // ok -- non-const return value    f5().modify(); // ok // causes compile-time errors: //! f7(f5()); //! f6() = x(1); //! f6().modify(); //! f7(f6()); } ///:~ 

why f5() = x(1) succed? going on here???

q1. when x(1) - going on here? constructor call - shouldn't read x::x(1); class instantiation - isn't class instantiation like: x a(1); how compiler determine x(1) is?? mean.. name decoration takes place so.. x(1) constructor call translate like: globalscope_x_int function name.. ???

q2. surely temporary object used store resulting object x(1) creates , would't assigned object f5() returns (which temporary object)? given f5() returns temporary object discarded, how can assign 1 constant temporary constant temporary??? explain why: f7(f5()); should reult in constant temporary , not plain old f5();

all questions boil down rule in c++ says temporary object (one has no name) cannot bound non-const reference. (because stroustrup felt provoke logical errors...)

the 1 catch, can invoke method on temporary: x(1).modify() fine f7(x(1)) not.

as temporary created, compiler job. rules of language precise temporary should survive until end of current full-expression (and no longer) important temporary instances of classes destructor has side-effect.

therefore, following statement x(1).modify(); can translated to:

{     x __0(1);     __0.modify(); } // automatic cleanup of __0 

with in mind, can attack f5() = x(1);. have 2 temporaries here, , assignment. both arguments of assignment must evaluated before assignment called, order not precise. 1 possible translation is:

{     x __0(f5());     x __1(1);     __0.operator=(__1); } 

(the other translation swapping order in __0 , __1 initialized)

and key working __0.operator=(__1) method invocation, , methods can invoked on temporaries :)


Comments

Popular posts from this blog

java - Play! framework 2.0: How to display multiple image? -

gmail - Is there any documentation for read-only access to the Google Contacts API? -

php - Controller/JToolBar not working in Joomla 2.5 -