悬空参考.悬挂指针和引用的替代方法? [英] Dangling reference. Alternatives for dangling pointers and references?

查看:174
本文介绍了悬空参考.悬挂指针和引用的替代方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码生成悬空的引用:

The following code produces dangling references:

int main()
{
  int *myArray = new int[2]{ 100, 200 };
  int &ref = myArray[0];
  delete[] myArray;
  cout << ref;  // Use of dangling reference.
}

我知道我不应该删除数组,但是在大型程序中,如果有人删除了我引用的内存该怎么办?能以某种方式确保没有人删除阵列吗?

I know I shouldn't delete the array but in a large program what if somebody deletes memory to which I have a reference? Can it be somehow assured that no one deletes the array?

针对悬挂引用和悬挂指针的最佳策略是什么?

What is the best strategy against dangling references and dangling pointers?

推荐答案

在完成内存操作之前,请不要删除它.

Don't delete the memory before you have finished with it.

听起来很愚蠢,但这是您唯一的保护-正确了解谁拥有每个变量背后的内存,以及何时可以安全地释放它.

Sounds stupid, but that's your only protection - properly understand who owns the memory behind each variable, and when it can safely be freed.

智能指针可以提供帮助,但以上内容仍然适用.

Smart pointers can help, but the above still applies.

有些静态分析工具可能会识别出您在这里遇到的琐碎情况,但即使如此,这也应该是第二道防线,您的第一条就是内存管理纪律.

It's possible some static analysis tools could identify the trivial case you have here, but even then that should be a second line of defence, with your first being discipline in memory management.

这篇关于悬空参考.悬挂指针和引用的替代方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆