我有:
Command *command;
if(commandType == "Start")
{
command = new StartCommand();
}
else if (commandType == "Stop")
{
command = new StopCommand();
}
现在假设我想command
成为一个shared_ptr,我如何翻译上面的代码来使用一个shared_ptr?
我有:
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)};
如评论中所示,您还可以违反 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>();
一些非常简单的更改将完成这项工作:
shared_ptr<Command> command;
if(commandType == "Start")
{
command = make_shared<StartCommand>();
}
else if (commandType == "Stop")
{
command = make_shared<StopCommand>();
}