【发布时间】:2013-12-08 11:31:32
【问题描述】:
我想使用 C++11 移动语义。我写了以下课程:
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));
我收到了复制构造函数调用。我做错了什么?
我以this 为例。并用g++编译。
这是我用于测试的 QT 项目:http://wikisend.com/download/261514/MoveConstructor.zip
【问题讨论】:
-
使移动构造函数为 noexcept。
-
@Kerrek SB - noexcept 有什么帮助?我已阅读您的回答stackoverflow.com/questions/8001823/…。比我看这个-msdn.microsoft.com/en-us/library/vstudio/dd293665.aspx。而在 MSDN 版本中没有 noexcept。
-
@tower120:考虑重新分配。重新分配必须要么完全成功,要么根本不发生。
-
@Kerrek SB 那么 MSDN 版本 msdn.microsoft.com/en-us/library/vstudio/dd293665.aspx 呢?
-
@tower120:问作者?
标签: c++11 stl move-semantics rvalue-reference