CS106L:Lecture 14:Move Semantics ppt笔记

张开发
2026/4/12 19:37:36 15 分钟阅读

分享文章

CS106L:Lecture 14:Move Semantics ppt笔记
Copy assignmentPhotoPhoto::operator(constPhotoother){if(thisother)return*this;//记得检查是否自己与自己比较delete[]data;//删除旧内存//复制...return*this;}lvalues rvalues左值lvalue persistent 有一个确定的地址✅a可以出现在左右任意一侧生命周期直到{}结束右值rvalue temporary 没有确定的地址❌a只能出现在右侧生命周期直到当前行末尾e.g.{1,2,3}c[2]c.size()都是右值c[1]是左值Type num左值引用Type num右值引用那么就可以重载两个传递参数分别为左值和右值的函数让编译器调用时决定选用哪一个Move SemanticsMove constructorType::(Type other)Move assignment operatorType Type::operator(Type other)copy后将要释放的内存的指针指向空 e.g.other.data nullptre.g. move constructorPhoto::Photo(Photoother):width(other.width),height(other.height),data(other.data)//inializer list{other.datanullptr;}e.g. move assignmentPhotoPhoto::operator(Photoother){if(thisother)return*this;delete[]data widthother.width heightother.height dataother.data other.datanullptr;return*this;}std::move如果我们知道某个左值后面不会再使用可以使用std::move,将左值强制转换为右值尽量不要显式调用std::move什么时候用SMFRule of Zero:如果一个类不会分配内存或其他额外资源不用 自定义任何SMFRule of Three:如果一个类分配了内存或额外资源我们必须自定义copy constructor/copy assignment否则两个对象可能会指向同一段数据Rule of Five:如果定义了copy constructor/copy assignment/destructor,那么为了避免不必要的复制同样需要定义move constructor/move assignment

更多文章