重複の可能性:
C++ の削除 - オブジェクトは削除されますが、データには引き続きアクセスできますか?
ローカル変数のメモリにスコープ外でアクセスできますか?
delete
で割り当てられたメモリを解放したいときに実際に何が行われるのかわかりませんnew
。C++ Premiere book では、次のように書かれています。
これにより、ps ポインタが指すメモリが削除されます。ポインター ps 自体は削除されません。たとえば、ps を再利用して、別の新しい割り当てを指すことができます。new の使用と delete の使用のバランスを取る必要があります。そうしないと、メモリ リークが発生する可能性があります。つまり、割り当てられたメモリが使用できなくなります。メモリ リークが大きくなりすぎると、より多くのメモリを求めるプログラムが停止する可能性があります。
したがって、私が理解delete
しているように、ピンターが指すメモリ内の値を削除する必要があります。しかし、そうではありません。これが私の実験です:
int * ipt = new int; // create new pointer-to-int
cout << ipt << endl; // 0x200102a0, so pointer ipt points to address 0x200102a0
cout << *ipt << endl; // 0, so the value at that address for now is 0. Ok, nothing was assigned
*ipt = 1000; // assign a value to that memory address
cout << *pt << endl; // read the new value, it is 1000, ok
cout << *((int *) 0x200102a0) << endl; // read exactly from the address, 1000 too
delete ipt; // now I do delete and then check
cout << ipt << endl; // 0x200102a0, so still points to 0x200102a0
cout << *ipt << endl; // 1000, the value there is the same
cout << *((int *) 0x200102a0) << endl; // 1000, also 1000 is the value
では、実際には何delete
をするのでしょうか?