移动构造与拷贝构造不同,拷贝构造故名思意需要复制内存,再删除原先内存。而移动构造则减少了内存的消耗,直接移动指针。而移动赋值则是对=的重载。
class StrV{
public:
StrV(StrV&&) noexcept;
StrV();
auto operator=(StrV &&that) noexcept -> StrV &;
private:
std::string *elements;
std::string *cap;
};
StrV that;
StrV::StrV(StrV &&that) noexcept {
// 将that通过移动构造给this
this->elements = that.elements;
this->cap = that.cap;
// 将that的成员设置为空
that.cap=that.elements= nullptr;
}
auto StrV::operator=(StrV &&that) noexcept -> StrV & {
if(this != &that){
// 释放this的已有元素
free();
this->elements = that.elements;
this->cap = that.cap;
// 将that置为可析够状态
that.cap=that.elements= nullptr;
}
return *this;
}
在移动构造后一般配合move()函数来使用。
ReadPageGuard::ReadPageGuard(ReadPageGuard &&that) noexcept {
Drop();// 释放已有元素
guard_ = BasicPageGuard(std::move(that.guard_));
}
auto ReadPageGuard::operator=(ReadPageGuard &&that) noexcept -> ReadPageGuard & {
Drop();//释放已有元素
guard_ = std::move(that.guard_);
return *this;
}
在实现了ReadPageGuard的移动构造后,可以直接将that的值move给其他对象的成员。
总结:移动构造很好的减少了拷贝构造的内存消耗,使得构造更加高效。务必记住在移动构造和移动赋值中需要先移除自身的元素并且结束时要将被移动对象置为可析构的状态。
其实具体可以参考c++vector<>中push_back()方法和emplace_back()方法。