In C++, what happens when you return a variable?
What happens, step by step, when a variable is returned. I know that if it's a built-in and fits, it's thrown into rax/eax/ax. What happens when it doesn't fit, and开发者_如何学运维/or isn't built-in? More importantly, is there a guaranteed copy constructor call?
edit: What about the destructor? Is that called "sometimes", "always", or "never"?
Where the return value is stored depends entirely on the calling convention and is very architecture- and system-specific.
The compiler is permitted to elide the call to the copy constructor (i.e., it does not have to call the copy constructor). Note that returning a value from a function might also invoke an assignment operator, depending on what is being done with the return value of a function.
If the function/method return type is a reference then effectively no copying takes place. If it is a non-reference return type, then a copy may take place depending on the calling convention of your platform.
In register-rich (typically RISC) architectures there may be a generous allocation of registers to hold modestly large return constructs. This is to avoid excessive memory transactions which are expensive compared to cache/register transactions.
On the x86-descended intel family which your question implies by the registers you mention, it is more likely than on a RISC to invoke a copy constructor.
精彩评论