有条件的shared_ptr建设
Conditional construction with 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)};
如注释中所述,您还可以违反 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>();
}
相关文章:
- CLANG 编译器 说:变量"PTR"可能未初始化
- 在以唯一ptr为值的C++映射中,动态内存何时会被销毁
- 将 ptr 传递给 ptr 到 A 作为参数传递给 A 的函数是不好的做法吗?
- 为共享 ptr 向量实现复制 c'tor?
- 字符和整数中 **(ptr+1) 的值差异
- C++:在不中断共享的情况下通过引用传递共享 PTR?
- 如何将派生类从基 ptr 分配给 nlohmann::json
- 引用 std::shared:ptr 以避免引用计数
- 为什么我不能在不进行任何转换的情况下将浮点数放入任何类型的 ptr 中?
- 在调用函数时,ptr** 和 ptr*& 之间是否有区别,或者首选C++?
- 另一种类型的智能ptr,比如具有弱refs的unique_ptr
- 尝试打印出 *ptr++ 的值,以了解它是如何工作的
- 如何控制共享 ptr 引用计数?
- C++中的指针否定 (!ptr == NULL)
- 从const ptr*转换为ptr*时出现问题
- 这是MSVC 2013中具有共享PTR的单例的正确实现吗?
- 对唯一 ptr 无效读取的引用向量
- C++ 类型转换基础 PTR 到派生 PTR 保存在引用类中
- 如何使用非类型参数传递模板化类的 Ref 或 Ptr
- 唯一 ptr 将所有权移动到包含对象的方法