Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > C++ > pass temporary object by value

Reply
Thread Tools

pass temporary object by value

 
 
Jarek Blakarz
Guest
Posts: n/a
 
      10-31-2012
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;
}
 
Reply With Quote
 
 
 
 
SG
Guest
Posts: n/a
 
      10-31-2012
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

 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
pass by value or pass by address? Vols C++ 3 04-27-2008 11:40 PM
anonymous array of strings // ("taking address of temporary"- how long is temporary valid?) anon.asdf@gmail.com C++ 7 02-12-2008 10:58 AM
Problem understanding pass by value and pass by reference of arrays and what happens in the memory venkatagmail C++ 11 10-03-2007 02:00 PM
creating a temporary object using dynamically created object Jess C++ 10 05-18-2007 02:21 PM
Pass by reference / pass by value Jerry Java 20 09-09-2005 06:08 PM



Advertisments