0

我有:

Command *command;

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

现在假设我想command成为一个shared_ptr,我如何翻译上面的代码来使用一个shared_ptr?

4

2 回答 2

4

跳过显而易见的,如果你想正确地初始化你的变量,例如如果它是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)};

如评论中所示,您还可以违反 C++ 的 RAII 指南并单独定义和初始化。不过,我仍然更喜欢使用std::shared_ptr<Command>::operator=over 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>();
于 2012-04-19T21:38:00.433 回答
0

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

shared_ptr<Command> command;

if(commandType == "Start")
{
  command = make_shared<StartCommand>();
}
else if (commandType == "Stop")
{
  command = make_shared<StopCommand>();
}
于 2012-04-20T05:11:24.280 回答