移动语义
参考下面的案例
#include<iostream>
#include <cstring>
struct A{
char*ptr;
A():ptr(new char[4096]){
}
A(const A& other){
std::cout<<"copy start"<<std::endl;
memcpy(ptr,other.ptr,4096);
}
~A(){
if(ptr) delete[]ptr;
}
};
A get_A(const A& a){
return a;
}
A make_A(){
A a;
return get_A(a);
}
int main(){
A a=make_A();
}
编译时加上-fno-elide-constructors避免RVO优化
g++ -fno-elide-constructors Mobile_semantics.cpp -o Mobile_semantics
./Mobile_semantics
可以看到发生了三次拷贝构造
- 第一次是get_A返回的A临时对象调用拷贝构造复制了a
- 第二次是make_A返回的A临时对象调用拷贝构造复制了get_A返回的临时对象
- 第三次是主函数a调用拷贝构造复制了make_A返回的临时对象
这段代码性能上存在极大的问题,产生的临时对象太多了,观察发现问题主要集中在第二次和第三次拷贝的过程,对此C++11引入了移动语义解决这个问题。
只需要对代码进行简单的修改即可减少大量资源消耗。
#include<iostream>
#include <cstring>
struct A {
char* ptr;
A():ptr(new char[4096]) {
}
A(const A& other):ptr(new char[4096]) {
std::cout << "copy start" << std::endl;
memcpy(ptr, other.ptr, 4096)