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引用实参这个语义限制,意在限制这个非常规用法的潜在错误。

相关推荐
长路 ㅤ   9 分钟前
Java后端技术博客汇总文档
分布式·算法·技术分享·编程学习·java后端
山河木马14 分钟前
前端学习C++之:.h(.hpp)与.cpp文件
前端·javascript·c++
2401_8919573115 分钟前
list的一些特性(C++)
开发语言·c++
秋说24 分钟前
【PTA数据结构 | C语言版】两枚硬币
c语言·数据结构·算法
二十雨辰25 分钟前
[尚庭公寓]07-Knife快速入门
java·开发语言·spring
Python大数据分析@27 分钟前
Origin、MATLAB、Python 用于科研作图,哪个最好?
开发语言·python·matlab
qq_5139704436 分钟前
力扣 hot100 Day37
算法·leetcode
编程零零七1 小时前
Python巩固训练——第一天练习题
开发语言·python·python基础·python学习·python练习题
不見星空1 小时前
leetcode 每日一题 1865. 找出和为指定值的下标对
算法·leetcode
我爱Jack1 小时前
时间与空间复杂度详解:算法效率的度量衡
java·开发语言·算法