欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 财经 > 金融 > 补充内存管理中的定位new

补充内存管理中的定位new

2025/3/28 22:45:34 来源:https://blog.csdn.net/2301_80159237/article/details/146485926  浏览:    关键词:补充内存管理中的定位new

        定位new表达式是在已分配的原始内存空间中调用构造函数初始化一个对象.

使用格式:

new (place_address) type或者new (place_address) type(initializer-list)

place_address必须是一个指针

initializer-list是类型的初始化列表

        使用场景定位new表达式在实际中一般是配合内存池使用。因为内存池分配出的内存没有初始化,所以如果是自定义类型的对象,需要使用new的定义表达式进行显示调构造函数进行初始化.

        下面看一些代码和注释来深入了解一下(因为还没有学习内存池的内容,所以暂时用operator new来开空间.

//定位new,内存管理的内容
class A
{
public:A(int a = 0):_a(a){cout << "A(int a = 0)" << endl;}~A(){cout << "~A()" << endl;}void Print(){cout << _a << endl;}
private:int _a;
};
int main()
{A* ptr1 = (A*) operator new(sizeof(A));new(ptr1)A;ptr1->Print();A* ptr2 = (A*) operator new(sizeof(A));new(ptr2)A(10);ptr2->Print();//如果不调用,operate delete不会调用析构ptr1->~A();ptr2->~A();operator delete(ptr1);operator delete(ptr2);return 0;
}
class A
{
public:A(int a = 0):_a(a){cout << "A(int a = 0)" << endl;}~A(){cout << "~A()" << endl;}void Print(){cout << _a << endl;}
private:int _a;
};
int main()
{//operator new只能初始化一个类型的大小的空间//要初始化多个要用operator new[]A* ptr1 = (A*) operator new[](sizeof(A)*10);//用定位new初始化,初始化为0~9for (int i = 0; i < 10; i++){new(ptr1 + (i * sizeof(A)))A(i);}//看构造结果for (int i = 0; i < 10; i++){(ptr1 + (i * sizeof(A)))->Print();}//析构for (int i = 0; i < 10; i++){(ptr1 + (i * sizeof(A)))->~A();}operator delete[](ptr1);return 0;
}

        以上就是我学习的定位new的内容啦.

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词