C++ 左值变右值

template<class T>
struct MyRemoveRef
{
	typedef T type;
};

void static_cast_test()
{
	std::string str = "hello";
	std::string str1 = "hello";
	std::string str2 = "hello";
	std::string str3 = "hello";


	//变右值方式1
	std::string test_str = static_cast<typename MyRemoveRef<std::string &&>::type &&> (str);

	//std::move也可以
	std::string test_str1 = std::move(str1);
	
	//变右值方式2
	std::string test_str2 = (static_cast<std::remove_reference_t<std::string> &&>(str2));

	//变右值方式3
	std::string test_str3 = static_cast<std::string &&> (str3);


	std::cout << "test_str:'" << test_str << "' and str: '" <<str <<"'" << std::endl;
	std::cout << "test_str1:'" << test_str1 << "' and str1: '" << str1 << "'" << std::endl;
	std::cout << "test_str2:'" << test_str2 << "' and str2: '" << str2 << "'" << std::endl;
	std::cout << "test_str3:'" << test_str3 << "' and str3: '" << str3 << "'" << std::endl;
}

 

### C++ 的概念及区别 在C++中,(lvalue)和(rvalue)是表达式分类中的两个重要概念。通常表示具有持久存储的实体,可以被取地址并多次使用;而则表示临时对象或字面量,通常不可取地址且生命周期较短。 #### 1. (lvalue) 是指能够出现在赋语句侧的表达式,它通常表示一个具有名字的对象,并且可以对其取地址。例如量名、数组元素等都属于[^3]。 ```cpp int a = 10; // 'a' 是 int& ref = a; // 引用 'ref' 绑定到 'a' ``` #### 2. (rvalue) 是指不能出现在赋语句侧的表达式,通常是临时对象或字面量。不能直接取地址,但在C++11之后引入了引用(rvalue reference),使得我们可以操作这些临时对象[^3]。 ```cpp int b = 20 + 30; // '20 + 30' 是 ``` #### 3. 区别总结 - **持久性**:通常表示具有持久存储的对象,而通常是临时对象或字面量。 - **可取地址性**:可以取地址,而通常不能取地址。 - **使用场景**:可以直接绑定到非const引用,而只能绑定到const引用或引用[^4]。 #### 示例代码 以下代码展示了的区别以及如何使用引用: ```cpp #include <iostream> using namespace std; void Func(int& x) { cout << "引用" << endl; } void Func(const int& x) { cout << "const引用" << endl; } void Func(int&& x) { cout << "引用" << endl; } void Func(const int&& x) { cout << "const引用" << endl; } template<typename T> void f(T&& t) { Func(t); // 根据参数t的类型去匹配合适的重载函数 } int main() { int a = 4; // f(a); // 调用引用版本[^1] const int b = 8; // const f(b); // 调用const引用版本[^1] f(10); // 调用引用版本[^1] const int c = 13; f(std::move(c)); // 调用const引用版本[^1] return 0; } ``` #### 关于万能引用 万能引用(universal reference)是C++中的一种模板机制,允许模板参数根据上下文自动推导为引用或引用。例如,在上述代码中,`f`函数的模板参数`T&&`会根据传入的实参类型自动调整为引用或引用[^2]。 ```cpp template<typename T> void tempFun(T&& t) { t = 40; cout << t << endl; } int main() { int x = 19; tempFun(x); // T为int&, t为int&,即得到引用[^2] tempFun(30); // T为int,t为int&&,即得到引用 int&& r = 100; tempFun(r); // 虽然r绑定到一个,但r量本身是个,因此得到引用 return 0; } ``` ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值