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

相关推荐
无敌最俊朗@25 分钟前
力扣hot100-206反转链表
算法·leetcode·链表
Kuo-Teng34 分钟前
LeetCode 279: Perfect Squares
java·数据结构·算法·leetcode·职场和发展
王哈哈^_^36 分钟前
YOLO11实例分割训练任务——从构建数据集到训练的完整教程
人工智能·深度学习·算法·yolo·目标检测·机器学习·计算机视觉
IMPYLH40 分钟前
Lua 的 collectgarbage 函数
开发语言·笔记·junit·单元测试·lua
百锦再1 小时前
第18章 高级特征
android·java·开发语言·后端·python·rust·django
檐下翻书1731 小时前
从入门到精通:流程图制作学习路径规划
论文阅读·人工智能·学习·算法·流程图·论文笔记
Tony Bai1 小时前
Go 在 Web3 的统治力:2025 年架构与生态综述
开发语言·后端·架构·golang·web3
CoderYanger1 小时前
B.双指针——3194. 最小元素和最大元素的最小平均值
java·开发语言·数据结构·算法·leetcode·职场和发展·1024程序员节
Charles_go1 小时前
C#中级、double和decimal有什么区别
开发语言·c#