Wednesday, November 24, 2010

User-defined Return Types

The following compiles:

class X
{ };

X funcX() 
{
  X x;
  return x;
}


int main() {
  X x2;
  funcX() = x2;
  return 0;
}

x2 is assigned to the temporary returned by funcx().

If a built-in type, such as int was used instead of class X, the program would not compile. This is because for built-in return types, rvalues are returned. For user-defined return types, lvalues are returned. In the user-defined case, it is useless to assign to a returned temporary, and so this is is usually a runtime bug.

No comments:

Post a Comment