C++ 返回后这是一个"invalid"引用吗?
C++ Is this an "invalid" reference after returning?
这显然很糟糕:
int& GetInvalidIntPtr(){
int i;
return i;
}
这是我的例子:
FVector& GetDirectionFromCamera(){
return GetActorLocation() - GetCameraComponent()->GetComponentLocation();
}
一个 FVector 基本上包含 3 个浮点数,这就是为什么我想要 return 引用而不是副本。不过,我相信计算的结果是存储在栈上的,对吧?
还是因为我立即 returning 它而在堆上分配了结果?
Or is the result allocated on the heap because I am immediatly returning it?
什么?那怎么会发生呢?编译器不只是神奇地在堆上分配东西,因为你 return 超出范围的东西。
试图优化掉三个浮点数的副本,冒着未定义行为的风险,因为你不明白代码真正在做什么,这是精神错乱。如果您不知道更好,那么只需 return 一份副本。这是简单而安全的选择。它也可能是最快的,因为简单的代码可以让编译器更好地优化。
An FVector basically holds 3 floats, that is why I'd like to return
the adress rather than a copy.
如果您想 return 地址,那为什么要 return 参考呢?引用不是指针。
(已删除,因为问题已被修改为使用单词 "reference" 而不是 "address"。)
However, I believe the result of the calculation is stored on the stack, right?
这实际上取决于您的 operator-
return 到底是什么。你没有给我们看,所以我们不能确定,但如果运算符只是 returns FVector
(应该如此),那么你的代码无法编译,因为临时 FVector
不能用于初始化 FVector&
.
通常,您的代码是基于这样一种误解,即 return FVector
的副本在某种程度上是不好的。它不是。将函数签名更改为 FVector GetDirectionFromCamera()
并让编译器删除冗余副本。
Or is the result allocated on the heap because I am immediatly returning it?
没有。你所说的 "heap" 只有在你使用动态分配时才会起作用。
这显然很糟糕:
int& GetInvalidIntPtr(){
int i;
return i;
}
这是我的例子:
FVector& GetDirectionFromCamera(){
return GetActorLocation() - GetCameraComponent()->GetComponentLocation();
}
一个 FVector 基本上包含 3 个浮点数,这就是为什么我想要 return 引用而不是副本。不过,我相信计算的结果是存储在栈上的,对吧?
还是因为我立即 returning 它而在堆上分配了结果?
Or is the result allocated on the heap because I am immediatly returning it?
什么?那怎么会发生呢?编译器不只是神奇地在堆上分配东西,因为你 return 超出范围的东西。
试图优化掉三个浮点数的副本,冒着未定义行为的风险,因为你不明白代码真正在做什么,这是精神错乱。如果您不知道更好,那么只需 return 一份副本。这是简单而安全的选择。它也可能是最快的,因为简单的代码可以让编译器更好地优化。
An FVector basically holds 3 floats, that is why I'd like to return the adress rather than a copy.
如果您想 return 地址,那为什么要 return 参考呢?引用不是指针。
(已删除,因为问题已被修改为使用单词 "reference" 而不是 "address"。)
However, I believe the result of the calculation is stored on the stack, right?
这实际上取决于您的 operator-
return 到底是什么。你没有给我们看,所以我们不能确定,但如果运算符只是 returns FVector
(应该如此),那么你的代码无法编译,因为临时 FVector
不能用于初始化 FVector&
.
通常,您的代码是基于这样一种误解,即 return FVector
的副本在某种程度上是不好的。它不是。将函数签名更改为 FVector GetDirectionFromCamera()
并让编译器删除冗余副本。
Or is the result allocated on the heap because I am immediatly returning it?
没有。你所说的 "heap" 只有在你使用动态分配时才会起作用。