从函数获取指向值结果的指针
Getting a pointer to a value result from a function
我正在使用一个仅通过函数调用提供和设置顶点位置的框架。例如
Point3 pos = mesh->GetVert(0);
mesh->SetVert(0, pos);
现在我正在尝试优化一个算法,该算法要求我遍历所有顶点并记住最后一个顶点,所以我尝试了这个:
Point3* current, last;
current = &mesh->GetVert(0);
for (int i = 1; i < mesh->VertCount(); i++) {
last = current;
current = &mesh->GetVert(i);
do stuff...
}
但我发现指针电流每次都设置为类似 0x12003 的值,并且从未实际指向 Point3 数据。我的印象是我尝试做的事情是可能的?毕竟,在处理相同框架的世界空间(美化矩阵)时,在查询函数调用成功之前添加 & returns 指向世界空间对象的指针。
现在很困惑,是什么给了我们?
这行代码:
current = &mesh->GetVert(0);
或许可以更形象地理解为:
{
Point3 _tmp_point = mesh->GetVert(0);
current = &_tmp_point;
// _tmp_point gets destroyed
}
// current points to destroyed temporary
(注意:我假设 GetVert
returns 是 Point3
而不是 Point3&
,否则你不会有任何问题)
基本上问题是 current
指向一个临时的 Point3
,它在赋值语句的末尾被销毁。所写的代码保证你有一个悬空指针!
简单的解决方法就是注意使用指针:
for (int i = 1; i < mesh->VertCount(); i++) {
Point3 current = mesh->GetVert(i);
// etc.
请注意,由于 Return Value Optimization,GetVert()
可能会在 current
中就地构造其返回的对象 - 因此这将是高效的。
我正在使用一个仅通过函数调用提供和设置顶点位置的框架。例如
Point3 pos = mesh->GetVert(0);
mesh->SetVert(0, pos);
现在我正在尝试优化一个算法,该算法要求我遍历所有顶点并记住最后一个顶点,所以我尝试了这个:
Point3* current, last;
current = &mesh->GetVert(0);
for (int i = 1; i < mesh->VertCount(); i++) {
last = current;
current = &mesh->GetVert(i);
do stuff...
}
但我发现指针电流每次都设置为类似 0x12003 的值,并且从未实际指向 Point3 数据。我的印象是我尝试做的事情是可能的?毕竟,在处理相同框架的世界空间(美化矩阵)时,在查询函数调用成功之前添加 & returns 指向世界空间对象的指针。
现在很困惑,是什么给了我们?
这行代码:
current = &mesh->GetVert(0);
或许可以更形象地理解为:
{
Point3 _tmp_point = mesh->GetVert(0);
current = &_tmp_point;
// _tmp_point gets destroyed
}
// current points to destroyed temporary
(注意:我假设 GetVert
returns 是 Point3
而不是 Point3&
,否则你不会有任何问题)
基本上问题是 current
指向一个临时的 Point3
,它在赋值语句的末尾被销毁。所写的代码保证你有一个悬空指针!
简单的解决方法就是注意使用指针:
for (int i = 1; i < mesh->VertCount(); i++) {
Point3 current = mesh->GetVert(i);
// etc.
请注意,由于 Return Value Optimization,GetVert()
可能会在 current
中就地构造其返回的对象 - 因此这将是高效的。