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
...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With