1

我对C++的返回值机制感到困惑,我写了以下代码来证明我的观点,代码的结果(有“?”在它之后,并且输出是粗体)让我感到困惑,谁能解释它为什么输出是这样,还是仅仅因为我的编译器供应商(MS Visual C++)为我优化?

#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;
}

输出是:

-----------

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
4

1 回答 1

1

这是返回值优化。您的编译器正在优化不必要的副本(尽其所能)。

编辑:检查这个问题以获得进一步的解释。

于 2013-07-13T04:19:39.727 回答