[英]double& (not passing by reference) C++
typedef double real8;
typedef real8 Real_t;
Real_t& x(int y);
What is Real_t&
?? 什么是Real_t&
?? I've only seen a datatype followed by "&" to indicate pass by reference. 我只看到一个数据类型后跟“&”表示通过引用传递。 But this is in declaration line. 但这是在申报行中。 What does this mean ? 这是什么意思 ?
This means that the function returns a reference to a Real_t
which is actually a double
. 这意味着该函数返回对Real_t
的引用,该实际上是一个double
。 The Real_t
is a real8
which is a double
if you resolve all the typedefs. Real_t
是一个real8
,如果您解析所有typedef,它是一个double
。
You should be careful here. 你在这应该小心。 If the result being passed by reference isn't retrieved from a scope that exists pasts the end of the function, then you'll have a dangling reference. 如果未通过函数结尾的范围检索通过引用传递的结果,那么您将有一个悬空引用。
For example: 例如:
int& foo() {
int x = 8;
return x;
}
int main() {
int y = foo();
}
The variable, y
, in main ends up referring to a variable which has been destroyed as it went out of scope when foo()
returned, so using it is undefined behavior . main中的变量y
最终引用一个变量,当foo()
返回时,该变量在超出范围时被销毁,因此使用它是未定义的行为 。 If x
had been retrieved from a singleton or something that lives outside the scope of the function foo()
, then it would still exist though and this would be fine. 如果x
是从单例或者函数foo()
范围之外的东西中检索到的,那么它仍然存在,这样就可以了。
People sometimes return references to initialize static globals in a deterministic way between compilation units, so you might see this used with statics like: 人们有时会在编译单元之间以确定的方式返回对初始化静态全局变量的引用,因此您可能会看到这与静态一起使用,如:
MyClass& MyStaticVar() {
static MyClass instance;
return instance;
}
Which is also okay, because the static lives for the duration of the program after initialized. 哪个也没关系,因为初始化后程序的持续时间是静态的。
It means x
is a function that returns a reference to a Real_t
. 这意味着x
是一个返回对Real_t
的引用的Real_t
。
An example of returning by reference is for data access in classes. 通过引用返回的示例是用于类中的数据访问。 For example, std::vector::at() returns a reference to an element of the vector. 例如, std :: vector :: at()返回对向量元素的引用。
For a free function to safely return a reference, there must be something non-obvious going on inside the function to ensure that a dangling reference isn't returned. 对于安全返回引用的自由函数,函数内部必须存在不明显的内容,以确保不返回悬空引用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.