将这种原始指针情况变成unique_ptr

Turning this raw pointer situation into a unique_ptr?

本文关键字:unique ptr 情况 原始 指针      更新时间:2023-10-16

我的代码看起来像这样:

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;