1 #include <bits/stdc++.h> 2 using namespace std; 3 typedef long long LL; 4 const int N=1e5+10; 5 const int INF=0x3f3f3f3f; 6 int cas=1,T; 7 struct node{ 8 int *p; 9 ~node() 10 { 11 cout<<"~node()\n"; 12 if(p) delete p; 13 } 14 }; 15 int main() 16 { 17 void * a=new float(3.0); 18 printf("%d %d\n",*((int*)a),(int)(*(float*)a)); 19 delete a; 20 printf("%d %d\n",*((int*)a),(int)(*(float*)a)); 21 a=new long long(3); 22 printf("%d %d\n",*((int*)a),(int)(*(long long*)a)); 23 delete a; 24 printf("%d %d\n",*((int*)a),(int)(*(long long*)a)); 25 node *b=new node; 26 b->p=new int(4); 27 int *c=b->p; 28 a=b; 29 delete a; 30 printf("p:%p\n",((node*)a)->p); 31 printf("%d\n",*c); 32 return 0;
1 請按 ENTER 或其它命令繼續 2 test.cpp: In function ‘int main()’: 3 test.cpp:19:9: warning: deleting ‘void*’ is undefined [-Wdelete-incomplete] 4 delete a; 5 ^ 6 test.cpp:23:9: warning: deleting ‘void*’ is undefined [-Wdelete-incomplete] 7 delete a; 8 ^ 9 test.cpp:29:9: warning: deleting ‘void*’ is undefined [-Wdelete-incomplete] 10 delete a; 11 ^ 12 13 請按 ENTER 或其它命令繼續 14 1077936128 3 15 0 0 16 3 3 17 0 0 18 p:(nil) 19 4 20 21 請按 ENTER 或其它命令繼續
void *a 原來的類型是float型,存的值是3.0,而後*((int*)a)直接強制將指針類型轉成int*以後輸出的值不是3,但(int)(*((float*)a))將a轉成float*以後再將值轉成(int)輸出的值就是3了,說明void*指針強制轉換後仍是會讀到原來的二進制,沒有進行指針所指向的值的轉換node
delete a以後兩個值都爲0說明delete void能成功delete void*成功,後面的結構體沒有輸出~node()說明沒有調用自定義類型的~node()函數,只是將該指針指向的內存free調,也說明系統會記住一個指針所指向的內存的大小c++
後面的long long結果不變說明void*強制轉換時若是大小不同採用尾截法取指向的內存ide