How to avoid successive deallocations/allocations in C++?

前端 未结 10 836
失恋的感觉
失恋的感觉 2021-02-07 18:26

Consider the following code:

class A
{
    B* b; // an A object owns a B object

    A() : b(NULL) { } // we don\'t know what b will be when constructing A

             


        
10条回答
  •  攒了一身酷
    2021-02-07 19:08

    Like the others have already suggested: Try placement new..

    Here is a complete example:

    #include 
    #include 
    
    class B
    {
      public:
      int dummy;
    
      B (int arg)
      {
        dummy = arg;
        printf ("C'Tor called\n");
      }
    
      ~B ()
      {
        printf ("D'tor called\n");
      }
    };
    
    
    void called_often (B * arg)
    {
      // call D'tor without freeing memory:
      arg->~B();
    
      // call C'tor without allocating memory:
      arg = new(arg) B(10);
    }
    
    int main (int argc, char **args)
    {
      B test(1);
      called_often (&test);
    }
    

提交回复
热议问题