Search code examples
c++chainingtemporary-objects

Chaining methods and temporary variables, please clarify


Greetings, everyone!

I have a class that receives a pointer to a "circle" (for example) and then adjusts its attributes via some "chaining" methods. Something like this:

class CCircleSetter
{
public:
   explicit CCircleSetter( CCirclePtr circle ) : m_circle(circle)
   {
   }

   CCircleSetter & Radius( int radius )
   {
       if (m_circle) m_circle->SetAttribute( "radius", radius );
       return *this;
   }
   CCircleSetter & Center( CPoint center )
   {
       if (m_circle) m_circle->SetAttribute( "center", center );
       return *this;
   }

   operator bool() const
   {
      return ( m_circle != NULL );
   }

private:
   CCirclePtr m_circle;
};

Now I wonder whether this code is legal or not:

if ( CCircleSetter(myCircle).Radius(10).Center(myPoint) ) 
{ ... }

On the one hand, I think that temporary object, created inside "if" expression, will live until the end of this expression. So, the calls to "Radius" and "Center" are legal. But on the other hand, it is an undefined behavior to use references to temporary variables and it seems to me that I am doing exactly this kind of thing - using (*this), where "this" is a temporary. It gives me some doubts, so, please, clarify. Thanks!


Solution

  • No, that's fine in this very specific case, because the temporary will be destroyed AFTER the whole line will execute, but in general is very bad to hold references to temporaries.