C++临时变量的常量性

C++ 临时变量的常量性-CSDN博客

cpp 复制代码
#include <iostream>
using namespace std;
void print(string& str) 
{
	cout << str << endl;
}

int main()
{
	print("hello world");
	//print(string("hello world"));
	return 0;
}

编译器根据字符串"hello world"构造一个string类型的临时对象,这个临时对象具有const属性,当这个临时变量传递给非const的string&引用类型时,无法隐式完成类型转换。

cpp 复制代码
#include <iostream>
using namespace std;
void print(const string& str) 
{
	cout << str << endl;
}

int main()
{
	print("hello world");
	//print(string("hello world"));
	return 0;

}

这样写是可以的。

临时变量作为引用参数传递时,形参必须是常量引用?

为什么呢?

cpp 复制代码
#include <iostream>
using namespace std;
class IntClass {
private:
	int x;
public:
	IntClass(int value) :x(value) {}
	friend  ostream& operator<<(ostream& os, const IntClass& intc);
};

 //重载 operator<<
ostream& operator<<(ostream& os, const IntClass& intc) {
	os << intc.x;
	return os;
}

int main(int argc, char* argv[]) {
	cout << (IntClass(6) = IntClass(8)) << endl;
}

结果是8

说明:

实际上临时变量是可以作为左值并被赋值的。

什么是左值?

这里这个友元函数我不是太懂。

IntClass(6)生成了一个无名临时变量并作为左值被修改,说明临时变量不是常量,只是编译器从语义层面限制了临时变量传递给非const引用。

临时变量所在的表达式执行结束后,它就会释放,所以修改一个临时变量是毫无意义的。

因此,C++编译器加入了临时变量不能作为非const引用实参这个语义限制,意在限制这个非常规用法的潜在错误。

相关推荐
LXS_35720 小时前
Day 05 C++ 入门 之 指针
开发语言·c++·笔记·学习方法·改行学it
MicroTech202520 小时前
微算法科技(MLGO)研发突破性低复杂度CFG算法,成功缓解边缘分裂学习中的掉队者问题
科技·学习·算法
墨染点香21 小时前
LeetCode 刷题【126. 单词接龙 II】
算法·leetcode·职场和发展
aloha_78921 小时前
力扣hot100做题整理91-100
数据结构·算法·leetcode
etsuyou21 小时前
js前端this指向规则
开发语言·前端·javascript
shizhenshide21 小时前
为什么有时候 reCAPTCHA 通过率偏低,常见原因有哪些
开发语言·php·验证码·captcha·recaptcha·ezcaptcha
Tiny番茄21 小时前
31.下一个排列
数据结构·python·算法·leetcode
挂科是不可能出现的21 小时前
最长连续序列
数据结构·c++·算法
mit6.8241 天前
[Agent可视化] 配置系统 | 实现AI模型切换 | 热重载机制 | fsnotify库(go)
开发语言·人工智能·golang
友友马1 天前
『 QT 』QT控件属性全解析 (一)
开发语言·前端·qt