c++ new 的相关

来源:互联网 发布:网上开店铺的软件 编辑:程序博客网 时间:2024/06/05 11:10

首先是一个链接  这里 说的很详细了

http://www.cnblogs.com/alephsoul-alephsoul/archive/2012/10/17/2728019.html

关于c++ new 的本质

=======

在上面基础上 要说的 是 new 和 malloc  的区别

 

首先是 malloc的相关用法

http://www.cnblogs.com/zhangyabin---acm/p/3188076.html

#include <iostream>#include <stdio.h>#include <stdlib.h>using namespace std;//测试大小端的宏static union {char c[4];unsigned int l;} endian_test = {{'l','?','?','b'}};#define ENDIANNESS ((char)endian_test.l)#pragma pack(4)struct MyStruct{char m_char;long  m_int;};class TestArray{public:TestArray(){cout<<"this is construct"<<endl;} ~TestArray() {cout<<"this is destruct"<<endl; }};int main(){  ///测试new一个数组时的指针前几个个字节是保留了 数组的长度       //当以下数组是int 或者MyStruct 时 向前取的值 完全是0       //  所以得出只对 自定义的class 才有意义TestArray* pArray =  new TestArray[257];int* pPoint = (int*)pArray  - 2;cout<<"the pre 4 byte's value is "<< *pPoint<<endl;printf("the pre  address is %p\n",pPoint);printf("the array  address is %p\n",pArray);char* pChar = (char*)pPoint;int array[8] = {0};for(int i = 0 ; i < 8; ++i){array[i] = *pChar;++pChar;cout<<"the " << i <<" byte 's value is " << array[i]<<endl;}    return 0;  }   

 

以下是区别

http://blog.csdn.net/zjc156m/article/details/16819357

 

最后是 new 在数组时需要注意的

http://blog.csdn.net/hazir/article/details/21413833

这里说的和详细

以上要补充的是

我在 mac  os 、64位机器 上  实验的效果是 自定义类  在new  数组时  实际返回指针的向前偏移8 个字节 后 取一个int * p 得到 数组的长度

但是 这里的只对 自定义的class  有意义, 基本类型 和 自定义的 struct  这里取到的是 0

见下面的代码

 

原创粉丝点击