Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Turning this raw pointer situation into a unique_ptr?

I have code that looks like this:

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;

Is there any way to do something like this but with unique_ptr?

That is, only ever having 1 call to update(data) instead of doing:

if(cond)
make unique
call update
end
if(cond)
make unique
call update
end
...
like image 284
jmasterx Avatar asked Dec 02 '22 16:12

jmasterx


1 Answers

Your code would be as simple as this:

    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;

You can check std::unique_ptr almost same way as you do with raw pointer

Notice how calling part could be simplified as a result of using RAII.

like image 70
Slava Avatar answered Dec 15 '22 14:12

Slava