What is the array form of 'delete'?

后端 未结 5 2090
时光取名叫无心
时光取名叫无心 2020-12-01 16:30

When I compiled a code using the array name as a pointer, and I deleted the array name using delete, I got a warning about deleting an array without using the a

5条回答
  •  感动是毒
    2020-12-01 16:37

    As the other have said, you must use the vector form of delete:

    void some_func(size_t n)
    {
      int* data = new int[n];
    
      . . . // do stuff with the array
    
      delete [] data; // Explicitly free memory
    }
    

    Be very wary of this, because some compilers will not warn you.

    Even better, there is very rarely any need for using vector new/delete. Consider whether your code can be altered to make use of std::vector:

    void some_func(size_t n)
    {
      std::vector data(n);
    
      . . . // do stuff with the array
    
    } // memory held by data will be freed here automatically
    

    And if you are dealing with the memory in a local scope, consider using STLSoft's auto_buffer, which will allocate from an internal buffer (held on the stack, as part of the instance) if possible, only going to the heap if it cannot:

    void some_func(size_t n)
    {
      stlsoft::auto_buffer data(n); // only allocates if n > 10
    
      . . . // do stuff with the array
    
    } // memory held by data will be freed here automatically, if any was allocated
    

    Read more about auto_buffer.

提交回复
热议问题