Get lvalue through rvalue

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • George2
    New Member
    • Dec 2007
    • 200

    Get lvalue through rvalue

    Hello everyone,


    I do not know how in the following code, rvalue -- return of X(), could result in a lvalue finally and binded to a non-const reference input parameter of function f.

    Any ideas?

    Code:
    struct X {
    
    
    };
    
    void f (X& x) {}
    
    int main()
    {
    	f (X() = X());
    
    	return 0;
    }

    thanks in advance,
    George
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    This is silly code.

    X() creates an X object by calling the default constructor. Therefore:

    X() = X()

    Creates two X objects and assigns the one on the right to the one on the left. That left object is bound as the non-const reference used on the call to f().

    The code above uis the same as:
    [code=cpp]
    X obj1;
    X obj2;
    obj1 = obj2;
    f(obj1);
    [/code]

    Comment

    • George2
      New Member
      • Dec 2007
      • 200

      #3
      Thanks weaknessforcats ,


      Do you think my original sample breaks the rule that non-const reference can not binded to a rvalue (temporary object return by X())?

      Originally posted by weaknessforcats
      This is silly code.

      X() creates an X object by calling the default constructor. Therefore:

      X() = X()

      Creates two X objects and assigns the one on the right to the one on the left. That left object is bound as the non-const reference used on the call to f().

      The code above uis the same as:
      [code=cpp]
      X obj1;
      X obj2;
      obj1 = obj2;
      f(obj1);
      [/code]

      regards,
      George

      Comment

      • weaknessforcats
        Recognized Expert Expert
        • Mar 2007
        • 9214

        #4
        Originally posted by George2
        Do you think my original sample breaks the rule that non-const reference can not binded to a rvalue (temporary object return by X())?
        Where did you hear this??

        Syntatically, you can always return a non-const pointer or reference to a local object. However, the the pointer or reference will become garbage once the temporary object disappears. On my compiler doing this generates a warning that I am doing is a bad thing.

        Comment

        • George2
          New Member
          • Dec 2007
          • 200

          #5
          Thanks for your advice, weaknessforcats !


          Originally posted by weaknessforcats
          Where did you hear this??

          Syntatically, you can always return a non-const pointer or reference to a local object. However, the the pointer or reference will become garbage once the temporary object disappears. On my compiler doing this generates a warning that I am doing is a bad thing.

          regards,
          George

          Comment

          Working...