因此,我尝试使用一些代码来查看在将值传递给函数时是否理解复制构造函数调用和析构函数调用。但是,我很困惑:
#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;
}
有人可以向我解释一下主要的第一行是什么吗?
为了解释我的困惑,根据我的理解,main应该在传递整数1时调用函数。因为Test'a_test'是函数的参数,并且它可以采用整数来构造,它是用传入的整数为1.然后我们返回'a_test',在这种情况下,应调用复制构造函数将'a_test'的内容复制到“返回值”的内容中。然后,应该调用析构函数来删除'a_test'中的内容。然后,应该为'test1'调用复制构造函数,以复制“返回值”的内容。然后,在我们完成复制内容之后,应该为析构函数调用“返回值”。
但是,我得到以下输出:
Constructor called
In 'function'
Returning
Copy constructor called
Destructor called
DONE WITH THIS ROUND
Constructor called
In 'function'
Returning
Copy constructor called
Copy assignment operator called
Destructor called
Destructor called
DONE WITH THIS ROUND
Destructor called
所以我似乎有错误的想法,感到完全困惑。 我期待:
Constructor called
In 'function'
Returning
Copy constructor called
Destructor called
Copy constructor called
Destructor called
DONE WITH THIS ROUND
....
然后输出的其余部分,如果我能理解第一行的第一行,我想我能理解。