首先明确定位new表达式:在已经分配好的原始内存空间调构造初始化。
new (place_address) type;
place_address是指针,指向已经分配的内存空间,type是类型。
举例说明:,拿一个简单的SeqList类来举例。
class SeqList
{
public:
SeqList(size_t n = 1)
:_a(new int[n])
{
cout << "构造函数" << endl;
}
~SeqList()
{
cout << "析构函数" << endl;
delete[] _a;
}
private:
int* _a;
};
int main()
{
SeqList* p1 = (SeqList*)operator new(sizeof(SeqList));
new(p1)SeqList;
p1->~SeqList();
operator delete(p1);
return 0;
}
可以看到,在创建空间之后,使用定位new表达式调用了它的构造函数,之后用使用指针的方式调用了析构函数后调用operator释放空间。
用宏实现动态内存开辟:
#define NEW(ptr,type) \
do{ \
ptr = (type*)operator new(sizeof(type)); \
new(ptr)type; \
} while (0);
开辟一片空间并使用定位new表达式,就是上文的方式.
#define DELETE(ptr,type) \
do{ \
ptr->~type(); \
operator delete(ptr); \
} while (0);
使用指针调用析构函数,释放空间,也是上文的方法。
#define NEW_ARRAY(ptr,type,n) \
do{ \
ptr = (type*)operator new(sizeof(type)*n+4); \
*((int*)ptr) = n; \
ptr = (type*)((char*)ptr+4); \
for(size_t i = 0; i<n; i++) \
{ \
new(ptr+i)type; \
} \
} while (0)
#define DELETE_ARRAY(ptr,type) \
do{ \
size_t n = *(((int*)ptr-1)); \
for(size_t i = 0; i<n; i++) \
{ \
(ptr+i)->~type(); \
} \
operator delete((char*)ptr-4); \
} while (0);