1

I puzzle over the return value mechanism of C++, and I write the following codes to testify my opion, and the result of the codes(has"?"after it, and the output is bold) confuses me, could anyone explain why it outputs like that, or just because my compiler vendor(MS Visual C++)optimizes for me?

#include <iostream>

class WInt
{
public:
    WInt( int a ) : a(a){ std::cout << a << " " << "A constructor" << std::endl; }
    WInt( const WInt& a )
    { 
        std::cout << "copy constructor run" << std::endl;
        this->a = a.a;
    }
    ~WInt(){ std::cout << "WInt destructor" << std::endl; }

    WInt& operator=( const WInt& v )
    {
        std::cout << "assignment operator" << std::endl;
        this->a = v.a;
        return *this;
    }

    friend const WInt operator+( const WInt& v1, const WInt& v2 )
    {
        return WInt( v1.a + v2.a );
    }

private:
    int a;
};

int main( int argc, char* argv[] )
{
    std::cout << "-----------" << std::endl;
    WInt a(1); // run constructor
    WInt b(2); // run constructor

    std::cout << "-----------" << std::endl;
    WInt c = a + b; // ???????????????????

    std::cout << "-----------" << std::endl;
    WInt d( a + b ); // ???????????????????

    std::cout << "-----------" << std::endl;
    c = a + b + c; // run the +, +, =, ~, ~

    std::cout << "-----------" << std::endl;
    WInt e = c; // run copy constructor

    std::cout << "-----------" << std::endl;

    return 0;
}

And the output is :

-----------

1 A constructor

2 A constructor

-----------

**3 A constructor**

-----------

**3 A constructor**

-----------

3 A constructor

6 A constructor

assignment operator

WInt destructor

WInt destructor

-----------

copy constructor run

-----------

WInt destructor

WInt destructor

WInt destructor

WInt destructor

WInt destructor
johnchen902
  • 9,531
  • 1
  • 27
  • 69
JavaBeta
  • 510
  • 7
  • 16

1 Answers1

1

This is return value optimization. Your compiler is optimizing the unnecessary copies (as best as it can).

EDIT: Check this question for further explanation.

Community
  • 1
  • 1
miguel.martin
  • 1,626
  • 1
  • 12
  • 27