C++11 分配返回的对象并复制构造函数和析构函数调用

C++11 分配返回的对象并复制构造函数和析构函数调用,c++11,constructor,destructor,copy-constructor,C++11,Constructor,Destructor,Copy Constructor,因此,我尝试用一些代码进行实验,看看在向函数传递值时是否理解复制构造函数调用和析构函数调用。然而,我感到困惑: #include <iostream> class Test { public: Test(int a) { std::cout<<"Constructor called"<<std::endl; } Test(const Test& copy) { std::cout

因此,我尝试用一些代码进行实验,看看在向函数传递值时是否理解复制构造函数调用和析构函数调用。然而,我感到困惑:

#include <iostream>

class Test
{
public:
    Test(int a)
    {
        std::cout<<"Constructor called"<<std::endl;
    }
    Test(const Test& copy)
    {
        std::cout<<"Copy constructor called"<<std::endl;
        this->a = copy.a;
    }

    Test& operator=(const Test& copy)
    {
        this->a = copy.a;
        std::cout<<"Copy assignment operator called"<<std::endl;
        return *this;
    }
    //Test& operator=(Test&& move) = delete;
    //Test(Test&& move) = delete;
    /*Test& operator=(Test&& move)
    {
        this->a = move.a;
        std::cout<<"Move assignment operator called"<<std::endl;
        return *this;
    }*/
    /*Test(Test&& move)
    {
        this->a = move.a;
        std::cout<<"Move constructor called"<<std::endl;
    }*/
    //invoked when passing 1...

    int a;
    ~Test()
    {
        std::cout<<"Destructor called"<<std::endl;
    }
};

Test function(Test a_test)
{
    std::cout<<"In 'function'"<<std::endl;
    std::cout<<"Returning"<<std::endl;
    return a_test;//copy constructor called to assign to temporary value that is being returned, and then destructor for a_test is called
}

int main()
{
    Test test1 = function(1);//copy constructor called again, and then destructor for temp value is called?
    std::cout<<"DONE WITH THIS ROUND"<<std::endl<<std::endl;
    test1 = function(1);//??
    std::cout<<"DONE WITH THIS ROUND"<<std::endl<<std::endl;
    return 0;
}
所以我似乎有错误的想法,感到完全困惑。 我期望:

Constructor called
In 'function'
Returning
Copy constructor called
Destructor called
Copy constructor called
Destructor called
DONE WITH THIS ROUND

....

然后是输出的其余部分,如果我能先理解main的第一行,我想我能理解。

我相信你在观察。编译器可以省略某些不必要的副本。正如Fred Larson所说,您确实观察到了副本省略和返回值优化。检查此链接:
Constructor called
In 'function'
Returning
Copy constructor called
Destructor called
Copy constructor called
Destructor called
DONE WITH THIS ROUND

....