有条件的shared_ptr建设

Conditional construction with shared_ptr?

本文关键字:ptr 建设 shared 有条件      更新时间:2023-10-16

我有:

Command *command;
if(commandType == "Start")
{
  command = new StartCommand();
}
else if (commandType == "Stop")
{
  command = new StopCommand();
}

现在假设我希望command成为shared_ptr,如何翻译上面的代码以使用shared_ptr?

跳过显而易见的,如果你想正确初始化你的变量,例如,如果它是const,你可以这样做

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)};

如注释中所述,您还可以违反 RAII 指南的C++和单独的定义和初始化。不过,我仍然更喜欢使用std::shared_ptr<Command>::operator=而不是std::shared_ptr<Command>::reset,因为它更直观,不会欺骗您new您永远不会delete的东西。

因此,例如,对于"Start"分支,这将如下所示:

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>();

一些非常简单的更改将完成这项工作:

shared_ptr<Command> command;
if(commandType == "Start")
{
  command = make_shared<StartCommand>();
}
else if (commandType == "Stop")
{
  command = make_shared<StopCommand>();
}