[英]C++: question on placement new in a union using Stroustrup example
[英]Question about array new placement in C++
我對 c++ 中數組的新位置有疑問。下面的代碼是我制作的示例代碼。
#include <vector>
#include <iostream>
class Point
{
int x,y;
public:
Point():x(0), y(0){std::cout<<"Point() : "<<this<<std::endl;}
void print(){std::cout<<x<<":"<<y<<std::endl;}
Point(int a, int b) :x(a), y(b){std::cout<<"Point(int,int) : value & addr "<<a<<":"<<b<<" ~ "<<this<<std::endl;}
~Point(){std::cout<<"~Point() : "<<this<<" "<<x<<":"<<y<<std::endl;}
};
int main()
{
// multiple allocation
void* mem_ptr_arr = operator new(sizeof(Point)*3);
for(int i=0; i<3; i++)
new( mem_ptr_arr+sizeof(Point)*i ) Point(i,i);
Point* ref_ptr_arr = static_cast<Point*>(mem_ptr_arr);
// delete process
for(int i=0; i<3; i++)
(ref_ptr_arr+i)->~Point();
operator delete(ref_ptr_arr);
Point* new_ptr = new Point[3]{};
delete[] new_ptr;
return 0;
}
我想復制新功能和刪除操作。 所以像下面這樣分解每個操作
我會這樣簡化:首先,只需分配具有低級別 function 的數組,如malloc()
或mmap()
、 brk()
並相應地處理它。 它有助於保持兩個世界的分離。
其次,在調用 placement new 時,如果您已經擁有該指針,則不一定需要使用它。
最后看起來你在做空指針運算,這是被禁止的。
// multiple allocation
Point* points = (Point*)std::malloc(sizeof(Point)*3);
for(int i=0; i<3; i++)
new ( &points[i] ) Point(i,i);
// delete process
for(int i=0; i<3; i++)
points[i].~Point();
std::free( points );
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.