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

相关推荐
ん贤2 小时前
Go channel 深入解析
开发语言·后端·golang
夜天炫安全3 小时前
数据结构中所需的C语言基础
c语言·数据结构·算法
2301_789015624 小时前
DS进阶:AVL树
开发语言·数据结构·c++·算法
Filotimo_6 小时前
5.3 Internet基础知识
开发语言·php
识君啊6 小时前
Java异常处理:中小厂面试通关指南
java·开发语言·面试·异常处理·exception·中小厂
qyzm8 小时前
天梯赛练习(3月13日)
开发语言·数据结构·python·算法·贪心算法
逆境不可逃8 小时前
LeetCode 热题 100 之 64. 最小路径和 5. 最长回文子串 1143. 最长公共子序列 72. 编辑距离
算法·leetcode·动态规划
leluckys8 小时前
swift- Swift中常见的面试题
开发语言·汇编·swift
BUG_MeDe8 小时前
json格式字符串解析的简单使用 libjson-c
c语言·开发语言·json
CoderCodingNo9 小时前
【GESP】C++五级练习题 luogu-P1182 数列分段 Section II
开发语言·c++·算法