C++ how to delete a structure?

前端 未结 11 1094
生来不讨喜
生来不讨喜 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:02

    delete newVideoSample . In C++ struct is the same as class but with default public fields.

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

    To Allocate -> VideoSample * newVideoSample = new VideoSample;

    To Delete -> delete newVideoSample;

    If you deleting the object in the same context, you better just allocate it on the stack. If you deleting it outside the context don't forget to pass a reference.

    And most important, don't delete if your about to exit process, it's pointless :P

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

    You're looking for the delete keyword:

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

    delete newVideoSample;

    However, consider using a smart pointer that will release the memory automatically, for example:

    std::auto_ptr<VideoSample> newVideoSample(new VideoSample);
    
    0 讨论(0)
  • 2020-12-31 04:09
    delete newVideoSample;
    

    But if the new and delete are in the same context, you're probably better off skipping them and just creating it on the stack instead:

    VideoSample newVideoSample = {buf, size};
    

    In that case, no cleanup is necessary.

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

    In C++ a structure is the exact same as a class except everything is public by default, where a class is private by default. So a structure can have a destructor and is freed with delete.

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