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

相关推荐
Never_Satisfied几秒前
在JavaScript / HTML中,关于querySelectorAll方法
开发语言·javascript·html
Thera77721 分钟前
【Linux C++】彻底解决僵尸进程:waitpid(WNOHANG) 与 SA_NOCLDWAIT
linux·服务器·c++
3GPP仿真实验室24 分钟前
【Matlab源码】6G候选波形:OFDM-IM 增强仿真平台 DM、CI
开发语言·matlab·ci/cd
Wei&Yan26 分钟前
数据结构——顺序表(静/动态代码实现)
数据结构·c++·算法·visual studio code
devmoon28 分钟前
在 Polkadot 上部署独立区块链Paseo 测试网实战部署指南
开发语言·安全·区块链·polkadot·erc-20·测试网·独立链
lili-felicity28 分钟前
CANN流水线并行推理与资源调度优化
开发语言·人工智能
沐知全栈开发29 分钟前
CSS3 边框:全面解析与实战技巧
开发语言
island131439 分钟前
CANN GE(图引擎)深度解析:计算图优化管线、内存静态规划与异构 Stream 调度机制
c语言·开发语言·神经网络
wregjru41 分钟前
【QT】4.QWidget控件(2)
c++
曹牧43 分钟前
Spring Boot:如何在Java Controller中处理POST请求?
java·开发语言