int &&i = 1; //i绑定到了右值1 int b = 2; cout << i << endl; //输出1 i = b; cout << i << endl; //输出2
int &&temp = 0; int &&i = temp;
int &&temp = 0; int &&i = 1; i = temp;
class A{ public: int b; int a; char c[256]; }; void f(A a) { ; } int main(int argc, char const *argv[]) { A &&a = A(); f(a); }
class A{ char *p; public: A(char *str){p = new char[strlen(str)+1]; strcpy(p , str);} A(const A& x){p = new char[strlen(x.p)+1]; strcpy(p , x.p);} ~A(){delete []p; p = NULL;} A& operator=(const A& x){ if(&x==this) return *this; delete []p; p = new char[strlen(x.p)+1]; strcpy(p , x.p); return *this; } } A f(){ A t(“1234"); return t; //创建返回值对象,调用拷贝构造函数用t对其初始化,随后对象t消亡 } int main(){ A a = “abcd”; a = f(); //调用重载的赋值操作符,把函数f返回的临时对象赋值给a,随后临时对象消亡 }
A(A&& x){p = x.p; x.p = NULL;}
编译程序发现t是即将消亡的对象,把它编译成调用转移构造函数。对象t消亡时不需要归还空间,等待返回值对象消亡才归还。
A &operator=(A&& x){ if(&x==this) return *this; delete []p; p = x.p; x.p = NULL; return *this; }
原文:https://www.cnblogs.com/yangyuliufeng/p/10720328.html