When passing an object Bar as a value to a function foo(), I noticed that the compiler (gcc) would construct a copy of the object outside of foo’s stack frame and then pass the newly constructed object’s reference to foo(). This behavior seems counter intuitive, what’s the reason for it?
Bellow are the C++ code I used and its correspondent assembly snippet from main
:
struct Bar
{
Bar(){}
Bar(const Bar& obj){}
};
Bar obj;
void foo(Bar obj){}
int main() {
foo(obj);
}
sub esp, 8
push OFFSET FLAT:obj
lea eax, [ebp-9]
push eax
call Bar::Bar(Bar const&) [complete object constructor]
add esp, 16
sub esp, 12
lea eax, [ebp-9]
push eax
call foo(Bar)
add esp, 16
New contributor
user25266923 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.