关于delete 就报错的问题

C++语言 码拜 8年前 (2016-04-25) 1271次浏览
#include <iostream>
#include <new>
using namespace std;
const int BUFF1=1024;
const int BUFF2=5;
int LEN[BUFF1];
int main()
{
int i,j;
int* p1,*p2;
p1=new int[BUFF2];
p2=new(LEN) int;

for(i=0;i<BUFF2;i++)
{
p1[i]=1000+20*i;
p2[i]=10*i;
cout<<“值p1=”<<p1[i]<<“\t”;
cout<<“地址p1=”<<&p1[i]<<“\t”;
cout<<“值p2=”<<p2[i]<<“\t”;
cout<<“地址p2=”<<&p2[i]<<endl;
}
delete[] p1;
delete[] p2;//释放p2就报错了!
return 0;
}
假如不delete[] p2,整个程序正常执行.一delete p2这个,就直接报错了。
本人想问,为什么p2不能delete,假如不delete p2,会不会造成内存泄露?

解决方案

50

new -> delete
new[] -> delete[]
new(pt) -> delete[] ??????
new-delete是匹配的
replacement new, 利用现有内存构造对象,
对应的 replacement delete,原因是一些原因不能直接调用(new(std::nothrow)也一样)
假如lz写过allocator,会发现是这样的:

 //    construction/destruction
    inline void construct(pointer p, const T& t) { new(p) T(t); }
    inline void destroy(pointer p) { p->~T(); }

也就说
replacement new对应的 replacement delete其实就是直接调用析构函数
也就是应该调用int的析构函数…也就是啥都不用干


CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明关于delete 就报错的问题
喜欢 (0)
[1034331897@qq.com]
分享 (0)