在C ++中传递引用到文字时会发生什么? [英] What happens when passing reference to literal in C++?
本文介绍了在C ++中传递引用到文字时会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这里会发生什么:
double foo( const double& x ) {
// do stuff with x
}
foo( 5.0 );
- 编译器是否创建一个匿名变量并将其值设置为5.0?
- x是否在只读存储器中引用了内存位置?这是一个奇怪的措辞,我知道...
编辑:我忘了const关键字.. 。
edit: I forgot the const keyword...
推荐答案
为此目的创建一个临时变量,它通常在堆栈上创建。
A temporary variable is created for this purpose and it's usually created on stack.
你可以尝试const_cast,但它无论如何,因为一旦函数返回,你不能再访问一个变量。
You could try to const_cast, but it's pontless anyway, since you can no longer access a variable once the function returns.
这篇关于在C ++中传递引用到文字时会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文