pass temporary object by value

Discussion in 'C++' started by Jarek Blakarz, Oct 31, 2012.

  1. 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;
    }
    Jarek Blakarz, Oct 31, 2012
    #1
    1. Advertising

  2. Jarek Blakarz

    SG Guest

    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
    SG, Oct 31, 2012
    #2
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Jerry
    Replies:
    20
    Views:
    7,927
    Roedy Green
    Sep 9, 2005
  2. Jess
    Replies:
    10
    Views:
    503
    James Kanze
    May 18, 2007
  3. venkatagmail
    Replies:
    11
    Views:
    681
    James Kanze
    Oct 3, 2007
  4. Replies:
    7
    Views:
    3,210
    James Kanze
    Feb 12, 2008
  5. Vols
    Replies:
    3
    Views:
    374
    Ian Collins
    Apr 28, 2008
Loading...

Share This Page