Search code examples
c++constructorshared-ptr

Conditional construction with shared_ptr?


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?


Solution

  • Skipping the obvious, if you want to properly initialise your variable, e.g. if it's const, you could do it like this

    std::shared_ptr<Command> factoryCommand(std::string const& commandType) {
      if(commandType == "Start")
        return std::make_shared<StartCommand>();
      if(commandType == "Stop")
        return std::make_shared<StopCommand>();
      return std::shared_ptr<Command>(nullptr);
    }
    
    std::shared_ptr<Command> const command {factoryCommand(commandType)};
    

    As 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= over std::shared_ptr<Command>::reset though, as it is more intuitive and doesn't trick you into newing something you will never delete.

    So, for the "Start" branch, for example, this would look like this:

    std::shared_ptr<Command> command;
    //...
    // I would flag this in the review process as "you're doing it wrong"
    command.reset(new StartCommand());
    // This is what you should do if you *have* to separate definition and initialisation:
    command = std::make_shared<StartCommand>();