C++ 为什么构造函数/析构函数只调用一次?
以下是我的源代码:C++ 为什么构造函数/析构函数只调用一次?,c++,c++11,constructor,destructor,C++,C++11,Constructor,Destructor,以下是我的源代码: #include <iostream> #include <memory> #include <vector> using namespace std; class Copy { public: Copy() { cout << "Constructor called" << endl; }; Copy(const Copy& copy) { c
#include <iostream>
#include <memory>
#include <vector>
using namespace std;
class Copy {
public:
Copy() {
cout << "Constructor called" << endl;
};
Copy(const Copy& copy) {
cout << "Copy constructor called" << endl;
}
Copy& operator=(Copy copy) {
cout << "Copy-Assign constructor called" << endl;
return *this;
}
Copy(Copy &©) noexcept {
cout << "Move constructor called" << endl;
}
Copy& operator=(Copy &©) noexcept {
cout << "Move-Assign constructor called" << endl;
return *this;
}
~Copy() {
cout << "Destructor called" << endl;
}
};
Copy TestCopy() {
Copy cop;
return cop;
}
vector<Copy> TestCopyVector() {
vector<Copy> copyVector = vector<Copy>{Copy()};
return copyVector;
}
int main()
{
Copy cop = TestCopy();
//TestCopy();
//vector<Copy> copyVector = TestCopyVector();
return 0;
}
应调用副本的移动分配。输出如下:
$ ./test
Constructor called
Destructor called
你能帮我解释一下吗?谢谢。调用了它,这是一个众所周知的优化,编译器可以在类似情况下进行优化。Copy cop=TestCopy()代码>无论如何都不会调用移动分配-此行中没有分配。在没有省略的情况下,它将调用move构造函数。
$ ./test
Constructor called
Destructor called