新的 move-constructor/move-operator 允许我们转移对象的所有权,从而避免使用(昂贵的)复制构造函数调用。但是是否可以避免构造临时对象(不使用返回参数)?
示例:在下面的代码中,构造函数被调用了 4 次——但理想情况下,我想做的是避免在 cross 方法中构造任何对象。使用返回参数(例如void cross(const Vec3 &b, Vec3& out)
是可能的,但很难读。我对更新现有变量感兴趣。
#include <iostream>
using namespace std;
class Vec3{
public:
Vec3(){
static int count = 0;
id = count++;
p = new float[3];
cout << "Constructor call "<<id <<" "<<p<< " "<<this<< endl;
}
~Vec3(){
cout << "Deconstructor call "<<id << " "<<p<<" "<<this<< endl;
delete[] p;
}
Vec3(Vec3&& other)
: p(nullptr) {
cout << "Move constructor call "<<id << " "<<p<<" "<<this<< endl;
p = other.p;
other.p = nullptr;
}
Vec3& operator=(Vec3&& other) {
cout << "Move assignment operator call from "<<other.id<<" to "<<id << " "<<p<<" "<<this<< endl;
if (this != &other) {
p = other.p;
other.p = nullptr;
}
return *this;
}
Vec3 cross(const Vec3 &b){
float ax = p[0], ay = p[1], az = p[2],
bx = b.p[0], by = b.p[1], bz = b.p[2];
Vec3 res;
res.p[0] = ay * bz - az * by;
res.p[1] = az * bx - ax * bz;
res.p[2] = ax * by - ay * bx;
return res;
}
float *p;
int id;
};
int main(int argc, const char * argv[])
{
Vec3 a,b,c;
a = b.cross(c);
return 0;
}