简体   繁体   中英

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?

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);
}

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);
      }
   }

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM