zoukankan      html  css  js  c++  java
  • c++ void*类型转换 delete void*

     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()
    ";
    12         if(p) delete p;
    13     }
    14 };
    15 int main()
    16 {
    17     void * a=new float(3.0);
    18     printf("%d %d
    ",*((int*)a),(int)(*(float*)a));
    19     delete a;
    20     printf("%d %d
    ",*((int*)a),(int)(*(float*)a));
    21     a=new long long(3);
    22     printf("%d %d
    ",*((int*)a),(int)(*(long long*)a));
    23     delete a;
    24     printf("%d %d
    ",*((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
    ",((node*)a)->p);
    31     printf("%d
    ",*c);
    32     return 0;
    test.cpp
     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 或其它命令继续
    result

    void *a 原来的类型是float型,存的值是3.0,然后*((int*)a)直接强制将指针类型转成int*之后输出的值不是3,但(int)(*((float*)a))将a转成float*之后再将值转成(int)输出的值就是3了,说明void*指针强制转换后还是会读到原来的二进制,没有进行指针所指向的值的转换

    delete a之后两个值都为0说明delete void能成功delete void*成功,后面的结构体没有输出~node()说明没有调用自定义类型的~node()函数,只是将该指针指向的内存free调,也说明系统会记住一个指针所指向的内存的大小

    后面的long long结果不变说明void*强制转换时如果大小不一样采用尾截法取指向的内存

  • 相关阅读:
    JDK源码那些事儿之LinkedBlockingQueue
    JDK源码那些事儿之并发ConcurrentHashMap上篇
    JDK源码那些事儿之ArrayBlockingQueue
    JDK源码那些事儿之HashMap.TreeNode
    mycat使用schema配置
    redis连接数高居不下,怎么破?。。。。这么破
    修改tomcat使用的的编码方式
    centos6.x下让redis以服务方式运行
    mycatrule
    HTML和XML中的转义字符
  • 原文地址:https://www.cnblogs.com/cdyboke/p/6908280.html
Copyright © 2011-2022 走看看