我已经搜索但找不到“何时”使用它们的答案。我只是一直听说它很好,因为它为我节省了额外的副本。我到处把它放在我上过的每一堂课中,但是对于某些课来说这似乎没有意义:S 我已经阅读了无数关于 LValues 和 RValues 以及 std::move vs. std::copy vs. memcpy 的教程与 memmove 等相比,甚至还阅读了 throw(),但我也不确定何时使用它。
我的代码如下所示:
struct Point
{
int X, Y;
Point();
Point(int x, int y);
~Point();
//All my other operators here..
};
然后我有一个类似的类数组(RAII sorta thing):
class PA
{
private:
std::vector<Point> PointsList;
public:
PA();
//Variadic Template constructor here..
~PA();
//Operators here..
};
我应该使用移动构造函数和复制构造函数吗?我在 Point Class 有它,但感觉很奇怪,所以我把它删除了。然后我在 PA 课上有了它,但我认为它不会做任何事情,所以我也删除了它。然后在我的位图类中,我的编译器抱怨有指针成员但没有重载,所以我做了:
//Copy Con:
BMPS::BMPS(const BMPS& Bmp) : Bytes(((Bmp.width * Bmp.height) != 0) ? new RGB[Bmp.width * Bmp.height] : nullptr), width(Bmp.width), height(Bmp.height), size(Bmp.size), DC(0), Image(0)
{
std::copy(Bmp.Bytes, Bmp.Bytes + (width * height), Bytes);
BMInfo = Bmp.BMInfo;
bFHeader = Bmp.bFHeader;
}
//Move Con:
BMPS::BMPS(BMPS&& Bmp) : Bytes(nullptr), width(Bmp.width), height(Bmp.height), size(Bmp.size), DC(0), Image(0)
{
Bmp.Swap(*this);
Bmp.Bytes = nullptr;
}
//Assignment:
BMPS& BMPS::operator = (BMPS Bmp)
{
Bmp.Swap(*this);
return *this;
}
//Not sure if I need Copy Assignment?
//Move Assignment:
BMPS& BMPS::operator = (BMPS&& Bmp)
{
this->Swap(Bmp);
return *this;
}
//Swap function (Member vs. Non-member?)
void BMPS::Swap(BMPS& Bmp) //throw()
{
//I was told I should put using std::swap instead here.. for some ADL thing.
//But I always learned that using is bad in headers.
std::swap(Bytes, Bmp.Bytes);
std::swap(BMInfo, Bmp.BMInfo);
std::swap(width, Bmp.width);
std::swap(height, Bmp.height);
std::swap(size, Bmp.size);
std::swap(bFHeader, Bmp.bFHeader);
}
它是否正确?我做了什么坏事或错事吗?我需要 throw() 吗?我的赋值和移动赋值运算符真的应该是一样的吗?我需要复印作业吗?啊这么多问题:c 我问的最后一个论坛无法回答所有问题,所以我很困惑。最后我应该使用 unique_ptr 作为字节吗?(这是一个字节/像素数组。)