placement new

参考:https://www.cnblogs.com/lustar/p/10717502.html

class A
{
public:
    A(int i) :a(i){}
    int getValue(){ return a; }
private:
    int a;
};

int main()
{
    A* p1 = new A(1);           //在堆上分配
    A  A2(2);                    //在栈上分配
    A* p2 = &A2;
    cout << "placement new前的值: " << p1->getValue() << "  " << p2->getValue() << endl;

    A* p3 = new(p1) A(3);       //在p1的位置上构造
    A* p4 = new(p2) A(4);       //在p2的位置上构造
    cout << "placement new后的值: " << p1->getValue() << "  " << p2->getValue() << endl;
}
posted @ 2021-03-10 15:23  kouei_kou  阅读(56)  评论(0编辑  收藏  举报