文章目录
文章最先发表于 peler的博客
起因
最近一直在看 《C++程序设计》 ,不得不说华章推出的**“黑皮书”系列质量是真的高。在这本书的“动态内存管理“**这一章里,有以下代码:
double *array = new delete[3];
delete[] array;
这段代码用 new[] 操作符创建了一个 double 数组,然后用 delete[] 操作符将数组删除。
实践
这就让我很不解啊, C++ 又不知道我创建的数组的长度,如何做到删除呢?我为此专门试了一下。为方便观察,增加了赋值和输出。
第一次实验
代码如下:
#include <iostream>
using namespace std;
int main(void)
{
double *array = new double[3]{
1,2,3};
cout<<array<<endl;
cout<<array[0]<<endl;
cout<<array[1]<<endl;
cout<<array[2]<<endl;
delete[] array;
cout<<array<<endl;
cout<<array[0]<<endl;
cout<<array[1]<<endl;
cout<<array[2]<<endl;
return 0;
}
输出如下:
0xe31760
1
2
3
0xe31760
7.35363e-317
7.35022e-317
3
整个事情就魔幻起来了,看样子,C++ 成功删除了数组的第1,2 个元素,但第三个元素没有删除。对了,g++ 编译器配置如下:
PS C:\Users\peler>g++ -v
Using built-in specs.
COLLECT_GCC=g++
COLLECT_LTO_WRAPPER=D:/Strawberry/c/bin/../libexec/gcc/x86_64-w64-mingw32/8.3.0/lto-wrapper.exe
Target: x86_64-w64-mingw32
Configured with: ../../../src/gcc-8.3.0/configure --host=x86_64-w64-mingw32 --build=x86_64-w64-mingw32 --target=x86_64-w64-mingw32 --prefix=/mingw64 --enable-shared --enable-static --disable-multilib --enable-languages=c,c++,fortran,lto --enable-libstdcxx-time=yes --enable-threads=posix --enable-libgomp --enable-libatomic --enable-lto --enable-graphite --enable-checking=release --enable-fully-dynamic-string --enable-version-specific-runtime-libs --enable-libstdcxx-filesystem-ts=yes --disable-libstdcxx-pch --disable-libstdcxx-debug --disable-bootstrap --disable-rpath --disable-win32-registry --disable-nls --disable-werror --disable-symvers --with-gnu-as --with-gnu-ld --with-arch=nocona --with-tune=core2 --with-libiconv --with-system-zlib --with-gmp=/opt/build/prerequisites/x86_64-w64-mingw32-static --with-mpfr=/opt/build/prerequisites/x86_64-w64-mingw32-static