Velocity Reviews

Velocity Reviews (http://www.velocityreviews.com/forums/index.php)
-   C++ (http://www.velocityreviews.com/forums/f39-c.html)
-   -   pass temporary object by value (http://www.velocityreviews.com/forums/t954076-pass-temporary-object-by-value.html)

Jarek Blakarz 10-31-2012 01:37 PM

pass temporary object by value
 
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;
}

SG 10-31-2012 01:54 PM

Re: pass temporary object by value
 
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



All times are GMT. The time now is 03:17 AM.

Powered by vBulletin®. Copyright ©2000 - 2013, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.


1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57