相关疑难解决方法(0)

C++放置新工作原理如何?

这个问题是为了确认我理解这个概念,并对使用方式和可能的优化方面采取专家意见.

我想了解"放置新",以下是我想出的程序......

 #include <iostream>
 #include <new>

 class A {
 int *_a;
 public:
 A(int v) {std::cout<<"A c'tor clalled\n";_a= new int(v);}
 ~A() {std::cout<<"A d'tor clalled\n"; delete(_a);}
 void testFunction() {std::cout<<"I am a test function &_a = "<<_a<<" a = "<<*_a<<"\n";}
};
int main()
{
    A *obj1 = new A(21);
    std::cout<<"Object allocated at "<<obj1<<std::endl;
    obj1->~A();
    std::cout<<"Object allocated at "<<obj1<<std::endl;
    obj1->testFunction();
    A *obj2 = new(obj1) A(22);
    obj1->testFunction();
    obj2->testFunction();
    delete(obj1);// Is it really needed now? Here it will delete both objects.. so this is not the …
Run Code Online (Sandbox Code Playgroud)

c++ placement-new

6
推荐指数
2
解决办法
1240
查看次数

标签 统计

c++ ×1

placement-new ×1