So I have a struct and a queue (modified, taken from here) in .h file of my class like:
struct VideoSample
{
const unsigned char * buffer;
int len;
};
concurrent_queue<VideoSample * > VideoSamples;
In .cpp file I have a function I run each time in a new thread, se开发者_JAVA百科nding into some arguments:
void VideoEncoder::AddFrameToQueue(const unsigned char *buf, int size )
{
VideoSample * newVideoSample = new VideoSample;
VideoSamples.try_pop(newVideoSample);
newVideoSample->buffer = buf;
newVideoSample->len = size;
VideoSamples.push(newVideoSample);
}
So as you see I try to keep VideoSamples with no more than one element in it (requirement).
I wonder will OS delete newVideoSample on thread distruction? Or how to delete it?
No. The OS will not delete that dynamically allocated VideoSample.
You'll have to do it when the thread ends.
It's hard to tell the lifetime of your objects from your post. If your VideoSamples is a member of the VideoEncoder class, and your VideoEncoder class is destroyed when the thread ends you could do it in the destructor of VideoEncoder. If your VideoSamples container gets destroyed when the thread ends, you could make VideoSamples hold some form of smart pointers to your VideoSample* to facilitate more automatic memory management.
You are also leaking memory if try_pop returns true, as you'll lose the pointer to your newly allocated VideoSample.
精彩评论