Copy Constructor -Query

Discussion in 'C++' started by Vivek Shah, Apr 29, 2004.

  1. Vivek Shah

    Vivek Shah Guest

    Hi,
    Given below is apiece of code which I was writing to clear my concepts
    of copy constructor. I have a function f() which takes Class A object
    through call by value and return the same object. Copy constructor is
    called when we pass the argument by value and we return from the
    function and also we initialize.

    In the main function, I check the number of time the copy constructor
    is called, I expect it to be 3
    (1) parameter passing in f(a)
    (2)return in f(a)
    (3) initialization of c = f(a)

    But it seems the copy constructor is called twice ..Why is that ?

    static int num;
    A::A(const A& A1)
    {
    cout<<" Inside COPY Constructor " <<++num <<endl;
    }


    const A f(const A z)
    {
    cout << "Inside Function" <<endl;
    return(z);
    }


    int main()
    {
    A a(5);
    A c = f(a); // c is initialized by return value of function f()
    cout << num; // Shouldnt num be 3 ...it is giving 2
    }

    Regards
    -Vivek Shah
     
    Vivek Shah, Apr 29, 2004
    #1
    1. Advertising

  2. "Vivek Shah" <> wrote...
    > Hi,
    > Given below is apiece of code which I was writing to clear my concepts
    > of copy constructor. I have a function f() which takes Class A object
    > through call by value and return the same object. Copy constructor is
    > called when we pass the argument by value and we return from the
    > function and also we initialize.
    >
    > In the main function, I check the number of time the copy constructor
    > is called, I expect it to be 3
    > (1) parameter passing in f(a)
    > (2)return in f(a)
    > (3) initialization of c = f(a)
    >
    > But it seems the copy constructor is called twice ..Why is that ?


    Read about "return value optimisation" or "RVO". The compiler is
    allowed to optimise the creation of a temporary away and return the
    object directly in your 'c'.

    Victor
     
    Victor Bazarov, Apr 29, 2004
    #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. VisionSet
    Replies:
    8
    Views:
    4,968
    Tris Orendorff
    Apr 29, 2004
  2. Aire
    Replies:
    3
    Views:
    489
    Mike Wahler
    Jan 25, 2004
  3. ali
    Replies:
    4
    Views:
    629
    David Harmon
    Mar 5, 2007
  4. Generic Usenet Account
    Replies:
    10
    Views:
    2,353
  5. cinsk
    Replies:
    35
    Views:
    2,734
    James Kanze
    Oct 11, 2010
Loading...

Share This Page