jmasterx
jmasterx

Reputation: 54103

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

Upvotes: 4

Views: 5796

Answers (3)

Marco A.
Marco A.

Reputation: 43662

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;

Upvotes: 3

Cory Kramer
Cory Kramer

Reputation: 117856

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;

Upvotes: 4

Slava
Slava

Reputation: 44238

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.

Upvotes: 10

Related Questions