pass temporary object by value

J

Jarek Blakarz

Hi

I can see that when passing by value a temporary object no copy constructor is
called.
Is it compiler's optimization ?
Is the object directly constructed inside "fun" function in the below program ?

thanks for answer.

class Human {};
void fun(Human h) {}

int main(void)
{
fun(Human());
return 0;
}
 
S

SG

Am 31.10.2012 14:37, schrieb Jarek Blakarz:
I can see that when passing by value a temporary object no copy constructor is
called.
Is it compiler's optimization ?

Yes. It's called "copy elision" and nearly always applicable whenever A
T-object is initialized with an rvalue of type T.
Is the object directly constructed inside "fun" function in the below program ?
thanks for answer.

class Human {};
void fun(Human h) {}

int main(void)
{
fun(Human());
return 0;
}

Yes, sort of. I'm not 100% sure but I believe that in modern
implementations a function parameter of non-trivial type that is passed
by value is actually passed "by pointer". This also applies to the
return value. The function is passed an additional parameter (address)
where the function is supposed to construct the return value into. So, I
expect something like this

string source();
void sink(string s);
int main() {
sink(source());
}

to be implemented like this (low level pseudo code):

void source(string* ret) {
// construct return value into *ret
}
int main() {
{
uninitualized string tmp;
source(&tmp);
sink(&tmp);
tmp.~string();
}
}

But for small and trivially copyable types it's probably done differently.

HTH,
SG
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,020
Latest member
GenesisGai

Latest Threads

Top