将这种原始指针情况变成unique_ptr
Turning this raw pointer situation into a unique_ptr?
我的代码看起来像这样:
ISessionUpdater* updater = nullptr;
if (eventName == "test")
updater = new TestJSONSessionUpdater(doc);
if (eventName == "plus")
updater = new PlusJSONSessionUpdater(doc);
if (updater)
{
bool result = updater->update(data);
delete updater;
return result;
}
return false;
除了unique_ptr
,有什么办法可以做这样的事情吗?
也就是说,只有 1 次调用 update(data)
而不是执行:
if(cond)
make unique
call update
end
if(cond)
make unique
call update
end
...
你的代码会像这样简单:
std::unique_ptr<ISessionUpdater> updater;
if (eventName == "test")
updater = std::make_unique<TestJSONSessionUpdater>(doc);
if (eventName == "plus")
updater = std::make_unique<PlusJSONSessionUpdater>(doc);
return updater ? updater->update(data) : false;
您可以像检查原始指针一样检查std::unique_ptr
请注意,通过使用 RAII,调用部分可以简化。
您可以使用
std::make_unique
分配一个新的std::unique_ptr
,如果它已经有一个,它将销毁旧的内部原始指针。
std::unique_ptr<ISessionUpdater> updater = nullptr;
if (eventName == "test")
updater = std::make_unique<TestJSONSessionUpdater>(doc);
if (eventName == "plus")
updater = std::make_unique<PlusJSONSessionUpdater>(doc);
if (updater)
{
bool result = updater->update(data);
return result;
}
return false;
>unique_ptr<>
有一个运算符布尔转换,可用于查询智能指针是否包含对象
std::unique_ptr<int> ptr;
if (ptr) // Not yet assigned
std::cout << "This isn't printed";
因此,您的代码成为
std::unique_ptr<ISessionUpdater> updater = nullptr;
if (eventName == "test")
updater = std::make_unique<TestJSONSessionUpdater>(doc);
if (eventName == "plus")
updater = std::make_unique<PlusJSONSessionUpdater>(doc);
if (updater) // If this smart pointer owns an object, execute the block
{
bool result = updater->update(data);
return result;
}
return false;
相关文章:
- 为什么 std::unique 不调用 std::sort?
- CLANG 编译器 说:变量"PTR"可能未初始化
- 在以唯一ptr为值的C++映射中,动态内存何时会被销毁
- 将 ptr 传递给 ptr 到 A 作为参数传递给 A 的函数是不好的做法吗?
- 为共享 ptr 向量实现复制 c'tor?
- 字符和整数中 **(ptr+1) 的值差异
- C++:在不中断共享的情况下通过引用传递共享 PTR?
- 生成"unique"矩阵
- 如何将派生类从基 ptr 分配给 nlohmann::json
- 引用 std::shared:ptr 以避免引用计数
- 我对 std::unique(算法)C++有问题
- 为什么我不能在不进行任何转换的情况下将浮点数放入任何类型的 ptr 中?
- 在调用函数时,ptr** 和 ptr*& 之间是否有区别,或者首选C++?
- 另一种类型的智能ptr,比如具有弱refs的unique_ptr
- 尝试打印出 *ptr++ 的值,以了解它是如何工作的
- 如何控制共享 ptr 引用计数?
- std::shared_ptr::unique(),复制和线程安全
- 如何在C++03中用自定义谓词调用std::unique
- C++中的指针否定 (!ptr == NULL)
- C++14 unique_ptr并使用已删除的函数'std::unique-ptr' unique_ptr错误