【问题标题】:Is the following code returning a reference to a stack object or is it valid?以下代码是返回对堆栈对象的引用还是有效?
【发布时间】:2018-08-20 06:22:09
【问题描述】:

我有这段代码,它通过引用返回值的 DLL 调用当前进程中的函数。我与之交谈的一个人说它是正确的,另一个人说它正在返回对堆栈对象的引用并且它是未定义的行为。我不确定哪个人更真实,因为我没有他们中任何一个人那么多的经验。

// Function call inside of the current process at a specific address. 
// Returns a matrix from the given meshcomponent and an id
FMatrix* GetMatrix(MeshComponent* mesh, FMatrix* result, int id) {
    return reinterpret_cast<FMatrix*(__fastcall*)(MeshComponent*, FMatrix*, int)>(address)(mesh, result, id);
}

// Gets the wanted 3D Vector out of the Matrix
void GetLocation(MeshComponent* mesh, FVector* result, int id) {
    FMatrix matrix;
    GetMatrix(mesh, &matrix, id);  <-- // When the function ends, is it possible for other stack operations to overwrite the matrix? Or is this valid?
    *result = static_cast<FVector>(matrix.WPlane);
}

// Usage, running from a DLL inside the process:
...
FVector location;
GetLocation(mesh, &location, id);
...

代码确实可以工作,但如果它确实返回了对堆栈对象的引用,我知道它可能随时中断,我会相应地对其进行更改。

【问题讨论】:

  • 什么是FVector 是指针吗?
  • 我没有看到任何代码返回对堆栈对象的引用。通过调用GetMatrix,您将一个指向堆栈对象的指针作为参数传递。
  • FVector 只是一个包含 {x, y, z} 的 3D Vector 结构体。
  • 元答案:让声称返回堆栈对象引用的人指出堆栈对象和所谓的对它的引用。证明不存在某事要困难得多,举证责任应该由提出易于验证的声明的人承担。
  • 感谢您的回答:)

标签: c++ object reference return stack


【解决方案1】:

根据你的评论

FVector 只是一个包含 {x, y, z} 的 3D Vector 结构体

这一行复制数据到result指向的位置

*result = static_cast<FVector>(matrix.WPlane);

没有通过引用返回。这方面的例子是

int& foo() {
    static int i;
    return i;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-02-03
    • 2016-12-27
    • 2011-11-25
    • 2021-06-19
    • 2012-07-28
    • 2011-02-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多