Turning this raw pointer situation into a unique_ptr?

5.5k views Asked by At

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
...
3

There are 3 answers

0
Slava On BEST ANSWER

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.

0
Marco A. On

unique_ptr<> has an operator bool conversion that can be used to query if the smart pointer holds an object

std::unique_ptr<int> ptr;
if (ptr) // Not yet assigned
   std::cout << "This isn't printed";

thus your code becomes

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;
0
Cory Kramer On

You can just assign a new std::unique_ptr using std::make_unique, and it will destroy the old internal raw pointer if it already has one.

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;