C ++删除指针两次 [英] C++ delete pointer twice

查看:217
本文介绍了C ++删除指针两次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道,当两个
指针指向同一个动态分配的对象时,可能会发生删除相同的内存两次错误。如果 delete
应用于其中一个指针,那么对象的内存将返回到
自由存储。如果我们随后删除第二个指针,那么
存储空间可能已损坏。

I know that a "deleting the same memory twice" error can happen when two pointers address the same dynamically allocated object. If delete is applied to one of the pointers, then the object’s memory is returned to the free store. If we subsequently delete the second pointer, then the free store may be corrupted.

但是为什么这个代码不会导致运行时错误? / p>

But why doesn't this code cause a run-time error?

 string *str_1 = new string;
  auto str_2 = str_1;
  *str_1 = "AAA";
  cout<<*str_2<<endl;
  delete str_1;
  delete str_2;  // No Error

    // Prints AAA


推荐答案

删除同一内存两次是未定义的行为。任何事情都可能发生,包括没有。它可以例如。稍后会导致崩溃。

Deleting the same memory twice is undefined behaviour. Anything may happen, including nothing. It may e.g. cause a crash sometime later.

这篇关于C ++删除指针两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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