为什么 constructor/destructor 被调用一次?
Why is the constructor/destructor called once?
这是我的源代码:
#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;
}
在我的理解中
Copy cop = TestCopy();
应该调用Copy的移动赋值。虽然输出如下所示:
$ ./test
Constructor called
Destructor called
有人能帮忙解释一下吗?谢谢
它被称为 RVO (Return value optimization),这是编译器在类似情况下允许进行的众所周知的优化。
这是我的源代码:
#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;
}
在我的理解中
Copy cop = TestCopy();
应该调用Copy的移动赋值。虽然输出如下所示:
$ ./test
Constructor called
Destructor called
有人能帮忙解释一下吗?谢谢
它被称为 RVO (Return value optimization),这是编译器在类似情况下允许进行的众所周知的优化。