std :: vector和Move构造函数

``````class ColorM
{
public:
ColorM(float _r, float _g, float _b, float _a){
qDebug()<<"Constructor";
r = _r;
g = _g;
b = _b;
a = _a;

m = new float[16];
}

ColorM(const ColorM &other){
qDebug()<<"Copy Constructor";
}

~ColorM(){
if (m != nullptr)
{
qDebug()<<"Deleting resource.";
// Delete the resource.
delete[] m;
}
}

// Move constructor.
ColorM(ColorM&& other)
{
qDebug()<<"Move Constructor";
r = other.r;
g = other.g;
b = other.b;
a = other.a;
m = other.m;

other.m = nullptr;
}

float r;
float g;
float b;
float a;

float *m;
private:
};
``````

``````std::vector<ColorM> vec;
vec.push_back(ColorM(0.1, 0.6, 0.3, 0.7));
vec.push_back(ColorM(0.2, 0.6, 0.3, 0.7));
vec.push_back(ColorM(0.3, 0.6, 0.3, 0.7));
``````

2 个答案:

``````std::vector<ColorM> vec;
vec.emplace_back(0.1, 0.6, 0.3, 0.7);  // Will call
vec.emplace_back(0.2, 0.6, 0.3, 0.7);  //     ColorM::ColorM(float _r, float _g, ..) ctor
vec.emplace_back(0.3, 0.6, 0.3, 0.7);
``````

``````std::vector<ColorM> vec;
vec.emplace_back(ColorM(0.1, 0.6, 0.3, 0.7));  // Should be equivalent to your code
vec.emplace_back(ColorM(0.2, 0.6, 0.3, 0.7));
vec.emplace_back(ColorM(0.3, 0.6, 0.3, 0.7));
``````