C++左值和右值问题

#include<iostream>

class Test
{
	public:
		Test(int n = 5){a = new int(n);std::cout<<a<<" c "<<*a<<std::endl;}
		~Test(){
			if(a){
				std::cout<<a<<" e "<<*a<<std::endl;
				delete a;
			}else{
				std::cout<<a<<" endl"<<std::endl;
			}
		}
		Test(Test&&c){
			std::cout<<"move construct"<<std::endl;
			delete this->a;
			this->a = c.a;

			c.a = NULL;
			std::cout<<"move end"<<std::endl;
		}
		Test(const Test& b){
			std::cout<<"copy construct"<<std::endl;
			*a = *b.a = 10;
			std::cout<<"e"<<b.a<<*b.a<<std::endl;
		}
		void show()&{
			std::cout<<a<<" s "<<*a<<std::endl;
		}
		void show()&&{
			std::cout<<"gg"<<std::endl;
		}
	private:
		int * a;
};


int main(){
	Test t = std::move(Test(1));
	Test && b = std::move(Test(2));
	b.show();		//访问一个已经被析构了的对象。这种用法是错误的
	Test().show();
	return 0;
}

/*

0xeb1648 c 1
move construct
move end
0 endl
0xeb1678 c 2
0xeb1678 e 2
0xeb1678 s 15407160
0xeb1678 c 5
gg
0xeb1678 e 5
0xeb1648 e 1

*/

右值是一个没有用户的对象,即一个临时匿名对象 。const引用可以延长匿名对象的声明周期,走 了身体。&&右值引用夺走了灵魂。内在的指针。

猜你喜欢

转载自blog.csdn.net/rubikchen/article/details/86531486
今日推荐