我想了解为什么下面的C++程序输出它的功能。C++:执行程序(构造函数,析构函数,赋值操作符等)
#include <iostream>
#include <vector>
#include <initializer_list>
#include <memory.h>
using namespace std;
// Constructors and memory
class Test{
static const int SIZE = 100;
int *_pBuffer;
public:
Test(){
cout << "constructor" << endl;
_pBuffer = new int[SIZE]{}; // allocated memory for int[size] and initialised with 'size' 0's
}
Test(int i){
cout << "parameterized constructor" << endl;
_pBuffer = new int[SIZE]{};
for(int i=0; i<SIZE; i++)
{
_pBuffer[i] = 7*i;
}
}
Test(const Test& other) // in the copy constructor we...
{
cout << "copy constructor" << endl;
_pBuffer = new int[SIZE]{}; // allocate the bytes then copy them from the 'other'
memcpy(_pBuffer, other._pBuffer, SIZE*sizeof(int));
}
Test &operator=(const Test &other){
cout << "assignment" << endl;
_pBuffer = new int[SIZE]{}; // allocate the bytes then copy them from the 'other'
memcpy(_pBuffer, other._pBuffer, SIZE*sizeof(int));
return *this;
}
~Test(){
cout << "Destructor" << endl;
delete [] _pBuffer;
}
};
ostream &operator<<(ostream &out, const Test &test)
{
out << "Hello from test";
return out;
}
Test getTest()
{
return Test();
}
int main() {
Test test1 = getTest(); // object gets created with default constructor =>
cout << test1 << endl;
vector<Test> vec;
vec.push_back(Test());
return 0;
}
这是我没有料到它的工作和我,它预计打印:
Test test1 = getTest();
在这里,我期待这样的事情发生:在getTest内部测试实例与构造函数与创建因此没有参数:cout < <构造函数;然后这个值被返回,并且用'='分配给test1,在这种情况下这将是'copy ctor',因此也是'copy ctor';
cout << test1 << endl;
在这里,我希望COUT < < “从测试你好”;曲子的重载“< <”
vector<Test> vec;
vec.push_back(Test());
在这里,我在等一个实例被创建并被推入VEC(1)与没有参数构造函数,以便COUT < <“构造” < < ENDL;
然后我期待TEST1和VEC(1)走出去的范围在程序,以便2X“COUT < <‘析构函数的结束’;”
所以,总体来说我的期望是这样的:
cout << constructor;
cout << copy constructor;
cout << hello from test;
cout << constructor;
cout << destructor;
cout << destructor;
然而该方案的实际工作输出是这样的:
constructor
Hello from test
constructor
copy constructor
Destructor
Destructor
Destructor
这是从我的期待:)不同。
在这些我想我能理解我最后得到的额外的析构函数。我想当函数getTest()返回一个赋值给test1的值时,该值也会在程序结束时被销毁,这就是为什么额外的析构函数。或者至少这是我的想法。如果我错了,请纠正我。
此外,我不明白为什么我没有得到一个“清点< <‘拷贝构造函数’”后“COUT < <‘构造’,”第一个。不是测试test1 = getTest();'呼叫复制ctor?
如果可能的话,请帮我理解这个程序的流程,这样我就能理解它为什么输出它所做的事情,并且更好地理解C++中的OOP。谢谢你的阅读。
那么偏差之一是构造函数是一个构造函数是一个构造函数。即使它是一个复制构造函数,它也用于构造对象,因此必须具有相应的析构函数调用。这就是为什么你的三个构造函数调用有三个析构函数调用。 –
由于[RVO](https://en.wikipedia.org/wiki/Return_value_optimization),您预期的第一个拷贝构造函数可能会被删除 – Default
顺便说一句,与您的问题无关,但您的任务中存在一个错误运营商。您在不释放旧内存的情况下分配新内存。实际上,由于构造函数已经分配了内存,所以在赋值操作符中根本就没有必要进行分配。 –