I have a strategy pattern, and would like to run it in a main loop in a game for example. The problem is there will be a memory leak If I’m not deleting the instance, and I also would like to use that instance somewhere else. How can I deal with memory allocation/deallocation in a strategy pattern.
CompressionContext *ctx = new CompressionContext();
//we could assume context is already set by preferences
ctx->setCompressionStrategy(new ZipCompressionStrategy());
//get a list of files
ctx->createArchive(fileList);
Use an
std::shared_ptr<CompressionContextBase>instead of aCompressionContextBase*(i.e. a raw pointer).Edit: This is just a suggestion, based on the information you provided, there may be other smart pointer implementations with different semantics, such as e.g.
unique_ptr, which might be more suited. As @akappa suggests, you may want to read up on the topic more, to make a better decision — again, based on the information in the question, you probably want ashared_ptrbut there might be additional considerations you omitted.