I have:
Command *command;
if(commandType == "Start")
{
command = new StartCommand();
}
else if (commandType == "Stop")
{
command = new StopCommand();
}
Now suppose I want command to be a shared_ptr, how do I translate the code above to use a shared_ptr?
Skipping the obvious, if you want to properly initialise your variable, e.g. if it’s
const, you could do it like thisAs indicated in the comments, you can also violate the RAII guideline of C++ and separate definition and initialisation. I would still prefer to use
std::shared_ptr<Command>::operator=overstd::shared_ptr<Command>::resetthough, as it is more intuitive and doesn’t trick you intonewing something you will neverdelete.So, for the
"Start"branch, for example, this would look like this: