Monday, May 24, 2010

C++: Is any compile time memory allocated for this type of function return value?

class c


{


c func()


{


return c();


}


}





I was rather amused to discover that this kind of object creation is allowed: as in return c(). This is obviously not an object declaration so I was wondering if memory is allocated at all compile time? I'm guessing that at runtime a temporary object automatically gets created just while returning. And this "temporary" memory is something different from the well known heap and stack memory areas??

C++: Is any compile time memory allocated for this type of function return value?
The memory for the result is allocated on the stack. However, the memory may be located purely in the caller of "c::func" and not in "c::func", itself, if your compiler uses return-value-optimization (RVO).
Reply:'return c();' will call the same function again, it is recursive, it will never complete recursing, eventually it will cause a stack overflow. No memory would be allocated at compile time. Stack memory will be allocated for each function call once c() is called.


No comments:

Post a Comment