C++ how to delete a structure?

前端 未结 11 1095
生来不讨喜
生来不讨喜 2020-12-31 03:42

Structure I created:

   struct VideoSample
  { 
      const unsigned char * buffer;
      int len;
  };

   VideoSample * newVideoSample = new VideoSample;
          


        
相关标签:
11条回答
  • 2020-12-31 04:16

    Use delete

    VideoSample * newVideoSample = new VideoSample;
    //.. stuffs
    
    delete newVideoSample;
    

    There is also an overload i.e delete[]

    VideoSample * newVideoSample = new VideoSample[n];
    //.. stuffs
    
    delete [] newVideoSample;
    

    In Modern C++ it is always recommended to use smart pointers. You may want to use boost::shared_ptr<T> from the boost library.

    0 讨论(0)
  • 2020-12-31 04:16

    If you intended VideoSample to free its buffer member then VideoSample is a fragile class. It has no way of knowing whether buf was created in the heap using new[] or malloc, or is the address of a variable on the stack.

    0 讨论(0)
  • 2020-12-31 04:18
    delete newVideSample;
    

    This won't free any memory you allocated to newVideoSample->buffer though - you have to free it explicitly before deleting.

    //Free newVideSample->buffer if it was allocated using malloc
    free((void*)(newVideSample->buffer));
    
    //if it was created with new, use `delete` to free it
    delete newVideSample->buffer;
    
    //Now you can safely delete without leaking any memory
    delete newVideSample;
    

    Normally this kind of freeing is written in the destructor of the class so that it'll be called automatically when you delete the dynamically created object.

    Thanks @steve for mentioning it :)

    0 讨论(0)
  • 2020-12-31 04:21

    Unless I'm missing something, you just use delete:

    delete newVideoSample;
    
    0 讨论(0)
  • 2020-12-31 04:26

    **You create object of Videosample , so you just use delete..

    VideoSample * newVideoSample = new VideoSample; delete newVideoSample;**

    0 讨论(0)
提交回复
热议问题