1

次のような状況があります。

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

    // code that breaks various laws of physics
}

しかし、ポインターが2つのタイプのいずれかになる可能性があるため、変更する必要がありますが、これを行うと:

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
}

が範囲外であるため、コンパイルに失敗します。

私は試した

std::unique_ptr<AClassBase>;

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

    // code that tweaks various laws of physics
}

しかし、ベースからではなくメンバー関数を使用する必要があり、ベースクラスのコードにアクセスできないため、これは失敗します。

これを回避する優雅な方法があるに違いありませんが、私には見えませんよね?

4

3 に答える 3

5

リファクタリングできますか

   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);
      }
   }
于 2012-05-17T15:22:21.580 に答える
5

が範囲外であるため、コンパイルに失敗します

メンバー関数を使用resetして修正します。

std::unique_ptr<AClassBase> a;

if (condition)
{
    if (whichOne)
        a.reset(new AClass);
    else
        a.reset(new BClass);
}
于 2012-05-17T15:05:13.573 に答える
0

1 つのオプションは、次を使用すること?:です。

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

しかし、個人的には、行全体が 70 文字以下に収まる場合にのみこれを行います。

それ以外の場合は、reset他の人が示唆しているように、作成後に共有ポインターのターゲットを設定するために を使用します。

于 2012-05-17T15:26:31.347 に答える