c++ - 删除运算符的确切操作

标签 c++ pointers delete-operator

我听说过很多关于 C++ delete operator 的事,到目前为止我也经常使用它,但我不知道是什么它的真正工作正是。
我在网上看到的是关于“取消分配存储空间”的讨论,但对我来说完全理解这个问题并没有多大意义。

请查看下面的代码片段。

int main()
{
   int* p = new int(6);
   cout << *p << endl;
   delete p;
}

指针 p 有自己的地址,因为它是一个变量 (#1)。指针 p 本身也有一个地址,因为它是一个指针(#2)。该对象(未命名)在其内存块中包含值 6,并且该内存块的地址与 #2 的地址相同。 (因为指针使用该地址指向该对象。)

现在,执行delete;后地址#1和#2会发生什么?
C++ 语言对此有何看法?
各种编译器对这种情况的影响是什么?

最佳答案

Now, what will happen over the address #1, #2 after executing delete; (in the code) please?

指针 p 将有一个未定义的值,但它会保留其地址(“#1”)。

*p 处的int 对象(地址为“#2”)不再存在。该地址现在描述了可在未来分配中免费使用的内存。


What does the C++ language say about this?

这个:

[C++14: 5.3.5/1]: The delete-expression operator destroys a most derived object (1.8) or array created by a new-expression. [..]

[C++14: 5.3.5/7]: If the value of the operand of the delete-expression is not a null pointer value, then:

  • If the allocation call for the new-expression for the object to be deleted was not omitted (5.3.4), the delete-expression shall call a deallocation function (3.7.4.2). The value returned from the allocation call of the new-expression shall be passed as the first argument to the deallocation function.
  • Otherwise, the delete-expression will not call a deallocation function (3.7.4.2).

And what can be the effect of various compilers on the case?

只要他们合规,就没有。所有编译器的行为方式必须相同。

关于c++ - 删除运算符的确切操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35525922/

相关文章:

c++ - 从参数包中获取 typedef

c++ - 为什么 if( constant == variable ) 比 if ( variable == constant ) 更受欢迎

c++ - 为什么不能 static_cast 双空指针?

c++ - 析构函数上的 =delete 如何防止堆栈分配?

c++ - 函数调用中的堆和删除。如何删除本地动态内存?

c++ - 如何在 C++ 中读取一个空文件?

c++ - 使用大循环的测试程序似乎中途挂起

c++ - 如何检查指针何时被删除?

C- 对指向可以为正数或负数的整数的指针数组进行排序

C++ 将指针分配给指针