我听说过很多关于 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/