为什么我的代码中没有调用移动构造函数?
How come the move constructor isnt called in my code?
#include <iostream>
#include<algorithm>
template<class T>
class Matrix {
std::pair<unsigned int,unsigned int> dim;
T* elem;
public:
Matrix(unsigned int d1, unsigned int d2) :
dim{std::make_pair(d1,d2)}, elem{new T[d1*d2]} { }
unsigned int size() const { return (dim.first)*(dim.second); }
Matrix(Matrix&& a){
std::cout<<"move constructor";
elem = a.elem;
a.elem =nullptr;
dim.first = a.dim.first+7;
dim.second = a.dim.second;
a.dim.first=0;
a.dim.second=0;
}
Matrix& operator=(Matrix&& a){
std::cout<<"move operator=";
elem = a.elem;
a.elem =nullptr;
dim.first = a.dim.first;
dim.second = a.dim.second;
a.dim.first=0;
a.dim.second=0;
return *this;
}
~Matrix() { delete[] elem; }
};
using namespace std;
int main() {
Matrix<unsigned int> bob = Matrix<unsigned int>(5,5);
Matrix<unsigned int> bob2(Matrix<unsigned int>(5,5));
return 0;
}//no output
我期待它打印 "move constructor" 和 "move operator="
但它都不打印它们。
Matrix(5,5) 没有名称,所以我假定它的右值,因此我希望 Matrix<unsigned int> bob = Matrix<unsigned int>(5,5);
调用移动构造函数
这是一项功能。
移动优于复制,但在这种情况下,C++ 甚至可以跳过移动!它被称为 elision 并且当你像这样初始化时最引人注目,或者从函数中初始化 return 。事实上,自 C++17 以来,我认为它甚至是有保证的;在过去,这只是允许的优化。请注意,即使构造函数有副作用(例如输出)也是允许的,这对于 C++ 来说是很不寻常的。
但是您的代码没有任何问题,确实可以正确地使用移动构造函数。否则代码将无法编译,因为仅当移动 could 已执行时才允许省略。
#include <iostream>
#include<algorithm>
template<class T>
class Matrix {
std::pair<unsigned int,unsigned int> dim;
T* elem;
public:
Matrix(unsigned int d1, unsigned int d2) :
dim{std::make_pair(d1,d2)}, elem{new T[d1*d2]} { }
unsigned int size() const { return (dim.first)*(dim.second); }
Matrix(Matrix&& a){
std::cout<<"move constructor";
elem = a.elem;
a.elem =nullptr;
dim.first = a.dim.first+7;
dim.second = a.dim.second;
a.dim.first=0;
a.dim.second=0;
}
Matrix& operator=(Matrix&& a){
std::cout<<"move operator=";
elem = a.elem;
a.elem =nullptr;
dim.first = a.dim.first;
dim.second = a.dim.second;
a.dim.first=0;
a.dim.second=0;
return *this;
}
~Matrix() { delete[] elem; }
};
using namespace std;
int main() {
Matrix<unsigned int> bob = Matrix<unsigned int>(5,5);
Matrix<unsigned int> bob2(Matrix<unsigned int>(5,5));
return 0;
}//no output
我期待它打印 "move constructor" 和 "move operator=" 但它都不打印它们。
Matrix(5,5) 没有名称,所以我假定它的右值,因此我希望 Matrix<unsigned int> bob = Matrix<unsigned int>(5,5);
调用移动构造函数
这是一项功能。
移动优于复制,但在这种情况下,C++ 甚至可以跳过移动!它被称为 elision 并且当你像这样初始化时最引人注目,或者从函数中初始化 return 。事实上,自 C++17 以来,我认为它甚至是有保证的;在过去,这只是允许的优化。请注意,即使构造函数有副作用(例如输出)也是允许的,这对于 C++ 来说是很不寻常的。
但是您的代码没有任何问题,确实可以正确地使用移动构造函数。否则代码将无法编译,因为仅当移动 could 已执行时才允许省略。