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

相关推荐
Swift社区9 分钟前
LeetCode 400 第 N 位数字
算法·leetcode·职场和发展
再难也得平10 分钟前
力扣239. 滑动窗口最大值(Java解法)
算法·leetcode·职场和发展
摩尔曼斯克的海12 分钟前
力扣面试题--双指针类
python·算法·leetcode
灰色小旋风24 分钟前
力扣——第7题(C++)
c++·算法·leetcode
Java基基1 小时前
Spring让Java慢了30倍,JIT、AOT等让Java比Python快13倍,比C慢17%
java·开发语言·后端·spring
future02101 小时前
Spring AOP核心机制:代理与拦截揭秘
java·开发语言·spring·面试·aop
Ralph_Y1 小时前
C++网络:一
开发语言·网络·c++
Hui Baby1 小时前
浅谈MCP原理
开发语言
2345VOR1 小时前
【QT的pyside6开发使用】
开发语言·qt
程序猿编码1 小时前
探秘 SSL/TLS 服务密码套件检测:原理、实现与核心设计(C/C++代码实现)
c语言·网络·c++·ssl·密码套件