通过将指向堆栈变量的指针传递给c++中的函数,我可以得到指向非预期位置的指针吗?

Can I end up with a pointer to an unintended location by passing a pointer to a stack variable to a function in C++?

本文关键字:指针 我可以 位置 c++ 变量 堆栈 函数      更新时间:2023-10-16

我知道编译器优化有时会导致堆栈帧波动。所以我的问题是,在c++中创建堆栈指针并将其传递给另一个函数并期望它指向被调用对象中的相同对象是否总是安全的。是否有可能因为编译器优化而最终指向一个意想不到的位置?

例如,这总是安全的任何编译器?

int main(){
   std::ofstream f("somefile");
   foo(&f);
   return 0;
}

或者我应该使用堆来获得一致的结果。

int main(){
   std::ofstream *f=new std::ofstream("somefile");  
   foo(f);
   close(*f);
   delete f;
   return 0;
}

当指针指向生命周期已经结束的对象时,就会创建悬浮指针:

std::string* s;
{
    std::string s1("hello");
    s = &s1;
}
// 's' now a dangling pointer because 's1' has been destructed.

这种情况在所发布的代码片段中都不存在,因此两者都是安全的。

在块中定义的对象的生命周期延伸到块的结束,无论在对象定义和块结束之间调用了哪些函数。因此,您的第一个示例没有问题。

您可能对相反的方法感到困惑:返回指向函数局部对象的指针是安全的:

std::ofstream * foo() {
  std::ofstream f("somefile");
  return &f;
}
int main() {
  std::ofstream * f = foo();
  // At this point there's no guarantee that f points to a valid object
}
相关文章: