新的移动构造函数/移动操作符允许我们传递对象的所有权,从而避免使用(昂贵的)复制构造函数调用。但是有没有可能避免构造临时对象(不使用返回参数)?
例如:在下面的代码中,构造函数被调用了4次——但理想情况下,我想做的是避免在cross方法中构造任何对象。使用返回参数(例如
例如:在下面的代码中,构造函数被调用了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;
}
other.p
设置为nullptr
。使用容器或智能指针来避免这种情况。 - awesoon