1.new 的简介:
new 是 C++ 中的关键字,尝试分配和初始化指定或占位符类型的对象或对象数组,并返回指向对象 (或数组的初始对象) 的指针。
C++
new (place_address) type
place_address 为一个指针,代表一块内存的地址。当使用上面这种仅以一个地址调用 new 操作符时,new 操作符调用特殊的 operator new:
C++
void * operator new (size_t, void *)
对于指定的地址的 new 对象,在释放时,不能直接调用 delete, 应该先调用对象的析构函数,然后再对内存进行释放。比如以下程序:
C++
include <iostream>
using namespace std;
int main(int argc, char* argv[])
{
char buf[100];
int *p=new (buf) int(101);
cout<<*(int*)buf<<endl;
return 0;
}
C++
int *arr = new int [100];
C++
#include <iostream>
class Test {
private:
int value;
public:
Test() {
printf("[Test] Constructor\n");
}
void* operator new(size_t size) {
printf("[Test] operator new\n");
return NULL;
}
};
int main()
{
Test* t = new Test();
return 0;
}
// [Test] operator new
// [Test] Constructor
阅读量:2010
点赞量:0
收藏量:0