我试图从C ++ 11中的新移动构造函数开始,遵循“Professional C ++”一书中的一个例子,第二版,第9章,第279页。
这是我的类头文件 Spreadsheet.h :
class Spreadsheet
{
public:
Spreadsheet(int inWidth = kMaxWidth, int inHeight = kMaxHeight);
Spreadsheet(const Spreadsheet& src);
Spreadsheet(Spreadsheet&& src);
~Spreadsheet();
int getId() const;
int getWidth() const;
int getHeight() const;
void setCellAt(int x, int y, const SpreadsheetCell& cell);
SpreadsheetCell getCellAt(int x, int y) const;
Spreadsheet& operator=(const Spreadsheet& rhs);
Spreadsheet& operator=(Spreadsheet&& rhs);
private:
bool inRange(int val, int upper) const;
void copyFrom(const Spreadsheet& src);
void moveFrom(Spreadsheet& src);
void freeMemory();
int mWidth, mHeight, mId;
SpreadsheetCell** mCells;
static int sCounter;
const static int kMaxWidth = 100;
const static int kMaxHeight = 100;
};
以下是 Spreadsheet.cpp 的一些摘录:
Spreadsheet::Spreadsheet(Spreadsheet&& src)
{
std::cout << "Move ctor" << std::endl;
moveFrom(src);
}
void Spreadsheet::moveFrom(Spreadsheet& src)
{
mId = src.mId;
mWidth = src.mWidth;
mHeight = src.mHeight;
mCells = src.mCells;
src.mWidth = 0;
src.mHeight = 0;
src.mCells = nullptr;
}
Spreadsheet& Spreadsheet::operator=(Spreadsheet&& rhs)
{
std::cout << "Move assignment" << std::endl;
if (this == &rhs) {
return *this;
}
freeMemory();
moveFrom(rhs);
return *this;
}
void Spreadsheet::freeMemory() {
for (int i = 0; i < mWidth; i++) {
delete [] mCells[i];
}
delete [] mCells;
mCells = nullptr;
}
然后,我在 main 上得到了这个:
std::vector<Spreadsheet> vec;
for (int i = 0; i < 3; i++) {
std::cout << "Iteration " << i << std::endl;
vec.push_back(Spreadsheet(1, 1));
std::cout << vec[i].getId() << std::endl;
std::cout << std::endl;
}
程序输出如下:
Iteration 0 Normal ctor Move ctor 0 Iteration 1 Normal ctor Move ctor Copy ctor 1 Iteration 2 Normal ctor Move ctor Copy ctor Copy ctor 3
我希望只是调用移动ctor而不是copy ctor来获取所有元素,而不仅仅是第一个元素,因为向量调整自身以适应新元素。
我正在使用clang 3.3-1和libc ++ 3.3-3进行编译:
$ clang++ -Wall -g -std=c++11 -stdlib=libc++ -lc++abi \
SpreadsheetTest.cpp Spreadsheet.o SpreadsheetCell.o -o SpreadsheetTest
我无法弄清楚的是,如果我的实现有问题,或者它与std::vector
实现有关,而不使用移动构造函数。