copy constructor is not called?

Discussion in 'C++' started by Yan, Mar 27, 2006.

  1. Yan

    Yan Guest

    Here is the code:

    #include <iostream>

    class A {
    public:
    A(){
    std::cout << "constructor" << std::endl;
    }
    A(const A&) {
    std::cout << "copy_constuctor" << std::endl;
    }
    ~A() {
    std::cout << "destructor" << std::endl;
    }
    };

    A foo() {
    return A();
    }

    int main() {
    A a = foo();
    return 0;
    }


    The output on the console is:

    constructor
    destructor

    I would expect it to be:
    constructor
    copy_constructor
    destructor
    destructor

    why isn't the second object being created? I thought the compiler
    (Cygwin version of gcc and Visual C++ ver 7.1) makes some optimizations
    that result in creating only one object, but even after disabling the
    optimization the result was the same. Can anyone please tell me what's
    happening here?

    Thanks!


    [ See http://www.gotw.ca/resources/clcm.htm for info about ]
    [ comp.lang.c++.moderated. First time posters: Do this! ]
     
    Yan, Mar 27, 2006
    #1
    1. Advertising

  2. Yan

    Phlip Guest

    Yan wrote:

    > A a = foo();


    Google for "Return Value Optimization". (And don't cross-post the easy
    questions to the moderated newsgroup, because you can get a simple answer
    faster than their moderation turnaround.)

    --
    Phlip
    http://www.greencheese.org/ZeekLand <-- NOT a blog!!!
     
    Phlip, Mar 27, 2006
    #2
    1. Advertising

  3. Yan

    Phlip Guest

    Phlip wrote:

    > Yan wrote:
    >
    >> A a = foo();

    >
    > Google for "Return Value Optimization".


    Oh, and that's not an "optimization", which just means the compiler takes
    longer to emit opcodes. It is a language feature, and is specifically
    defined as you shall not depend on the number of times a return value
    copy-constructs.

    --
    Phlip
    http://www.greencheese.org/ZeekLand <-- NOT a blog!!!
     
    Phlip, Mar 27, 2006
    #3
    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. Apricot
    Replies:
    4
    Views:
    546
    velthuijsen
    Apr 16, 2004
  2. Replies:
    9
    Views:
    1,856
    Alf P. Steinbach
    Oct 14, 2006
  3. Replies:
    11
    Views:
    1,008
    Nindi
    Nov 14, 2006
  4. suresh
    Replies:
    2
    Views:
    393
    Andrey Tarasevich
    Apr 15, 2008
  5. cinsk
    Replies:
    35
    Views:
    2,653
    James Kanze
    Oct 11, 2010
Loading...

Share This Page