Stefan
Stefan

Reputation: 3859

unique_ptr setup

I have the following situation:

if (condition)
{
    std::unique_ptr<AClass> a(new AClass);

    // code that breaks various laws of physics
}

But I need to change it as the pointer could now be one of two types but if I do this:

if (condition)
{
    if (whichOne)
        std::unique_ptr<AClass> a(new AClass);
    else
        std::unique_ptr<AClass> a(new BClass);

    // code that fixes various laws of physics
}

It fails to compile as a is out of scope.

I tried

std::unique_ptr<AClassBase>;

if (condition)
{
    if (whichOne)
        a(new AClass);
    else
        a(new BClass);

    // code that tweaks various laws of physics
}

But this fails as a needs to use member function not from the base and I do not have access to the code for the base class.

There must be a graceful way around this but I cannot see it, can you?

Upvotes: 1

Views: 301

Answers (3)

Edward Loper
Edward Loper

Reputation: 15944

One option is to use ?::

std::unique_ptr<AClassBase> a(whichOne ? (new AClass) : (new BClass));

But I'd personally only do this if the whole line can fit in under 70 characters or so.

Otherwise, I'd use reset, as others have suggested, to set the shared pointer's target after it is created.

Upvotes: 0

Dave S
Dave S

Reputation: 21058

Can you just refactor into

   std::unique_ptr<AClassBase> base;
   if( condition ) 
   {
      if(whichone)
      {
         std::unique_ptr<AClass> a(new AClass);
         // Break laws of physics with an AClass

         base = std::move(a);
      }
      else
      {
         std::unique_ptr<BClass> b(new BClass);
         // Break laws of physics with an BClass

         base = std::move(b);
      }
   }

Upvotes: 5

Maxim Egorushkin
Maxim Egorushkin

Reputation: 136208

It fails to compile as a is out of scope

Use reset member function to fix that:

std::unique_ptr<AClassBase> a;

if (condition)
{
    if (whichOne)
        a.reset(new AClass);
    else
        a.reset(new BClass);
}

Upvotes: 5

Related Questions