简体   繁体   中英

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 (ie, 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM