通过将指向堆栈变量的指针传递给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++中创建堆栈指针并将其传递给另一个函数并期望它指向被调用对象中的相同对象是否总是安全的。是否有可能因为编译器优化而最终指向一个意想不到的位置?
例如,这总是安全的任何编译器?
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
}
相关文章:
- 函数向量_指针有不同的原型,我可以构建一个吗
- 我可以制作指向智能指针的智能指针吗?
- 在C++中,如果我可以直接将整数分配给指针而不使用"new",为什么要使用"new"?
- 如果我在 const 函数上使用指针,我可以返回什么?
- 我可以有一个 ELI5 作为参考和指针以及何时使用它们吗?
- 我可以使用 decltype() 或其他东西通过指针获取真实类型吗?
- 我可以做些什么来改进指针向量中的此搜索?
- 如何将 c++ 类包装到 python 中,以便我可以使用 pybind11 访问其成员的公共方法(成员是一个对象指针)
- 如果我知道只会使用现有元素,我可以在数组开头之前传递指针吗?
- 我可以直接为指针分配地址吗?如果是,如何做到这一点
- 我可以在初始化之前使用 std::array 成员变量中的 data() 指针吗?发出警告
- 为什么我可以通过原始指针而不是shared_ptr来修改对象
- 为什么我可以通过野生指针调用成员函数
- 在C++我可以在不在本地声明结构的情况下将结构作为指针传递吗?
- 为什么我可以取消引用指向抽象类的指针?
- 我可以保证以负偏移访问指针吗?
- 我可以更改将引用参数传递到指针中并使其正常工作的函数的输入(C、C++)吗?
- 我可以从构造函数内传递会员函数指针吗?
- 为什么我可以更改指针的常数(const char *)槽的值
- 我可以依靠 initializer_list::const_iterator 是一个普通的指针吗?