C++0x中加入了右值引用,和move函数。
通过move操作可以减少不必要的内存分配.c++ 对string,set等都加入了move操作,增加效率.
那如果我们自定义类的时候,如果类中的变量没有能move操作的变量,是否写了移动构造函数事没有效果的?
例子如下
#include <iostream>
#include <utility>
#include <vector>
#include <string>
using namespace std;
class MyPoint{
public:
MyPoint()
:comment(""), x(0), y(0)
{
}
MyPoint(const MyPoint& p)
:comment(p.comment),x(p.x),y(p.y)
{cout<<"copy is called"<<endl;}
MyPoint(MyPoint&& p)
:comment(move(p.comment)), x(move(p.x)), y(move(p.y))
{
cout<<"move is called"<<endl;
// p.x = 0;
// p.y = 0;
}
string toString()
{
char buf[100];
sprintf(buf, "%s: %d %d", comment.c_str(), x, y);
return buf;
}
string comment;
int x;
int y;
};
int main()
{
MyPoint p;
p.comment = "First point";
p.x = 9;
p.y = 7;
vector<MyPoint> v;
MyPoint p1(std::move(p));
cout<<p.x<<" "<<p.y<<endl;
cout<<p.comment<<endl;
cin.get();
}
结果:
move is called
9 7
comment的值被转移了,p的x,y还在
那,如果去除类中的comment属性,那么移动构造函数还有没有存在必要.
没必要,基本类型本来就是值语义,
右值引用只是一种类型而已,编译器并不会为它增加什么额外的功能,
它的功能还是由你来定义了,如果你觉得没用,大可不必定义