【问题标题】:How can I create a vector of type Interface& in C++?如何在 C++ 中创建 Interface& 类型的向量?
【发布时间】:2023-02-16 17:21:59
【问题描述】:

这是代码:

#include <iostream>


class Interface_A
{
  public:virtual bool dothething () = 0;
};


class Inherit_B:public Interface_A
{
  bool dothething ()
  {
    std::cout << "Doing the thing in B\n";
    return true;
  }
};

class Inherit_C:public Interface_A
{
  bool dothething ()
  {
    std::cout << "Doing the thing in C\n";
    return true;
  }
};

/**This works */
Interface_A& makeBC ()
{
 #ifdef make_B
  return *(new Inherit_B ());
 #elif make_C
  return *(new Inherit_C());
 #endif
}

/**This doesn't work 
Interface_A makeC ()
{
 #ifdef make_B
  return ((Interface_A) (new Inherit_B ()));
 #elif make_C
  return ((Interface_A) (new Inherit_C ()));
 #endif
}
*/

int main ()
{
  Interface_A& obj = makeBC ();
  obj.dothething();
  // ultimate goal is to make a vector of type <Interface_A&>
  return 0;
}

我想最终创建一个类型为 &lt;Interface_A&amp;&gt; 的向量,但我似乎无法找到一种方法来做到这一点。创建 &lt;Interface_A&gt; 类型的向量也可以,但据我所知,c++ 不允许创建对抽象类型的指针引用。
我不能使用返回类型 Inherit_B 因为 Interface_A 被多个类继承并且活动类是在编译时确定的。 我不能使用智能指针,因为性能是代码的一个极其关键的方面。
我如何为此制定通用解决方案?

【问题讨论】:

  • std::vector&lt;Interface_A*&gt; 到底有什么问题?或者更好的std::vector&lt;unique_ptr&lt;Interface_A&gt;&gt;

标签: c++ c++11 pointers interface pass-by-reference


【解决方案1】:

std::reference_wrapper 允许您在容器中存储引用。但是,您不需要参考。引用引用对象。您需要的是将对象存储在某处在向量中保留指向它的指针。那是一个std::vector&lt;std::unique_ptr&lt;Interface&gt;&gt;

我不能使用智能指针,因为性能是代码的一个极其关键的方面。

这是一个有争议的问题。当您决定使用继承和运行时多态性时,您已经购买了间接级别。智能指针不会带来额外的开销,但它们是适合您所处情况的正确工具。

如果你想避免这种间接级别,那么你应该重新考虑使用运行时多态性。

...活动类在编译时确定

我们开始了......你不需要运行时多态性。您的示例过于模糊和抽象,无法提出更好的设计。但是当您不需要运行时多态时,您当然不想为此付费。

【讨论】:

    猜你喜欢
    • 2021-08-25
    • 1970-01-01
    • 1970-01-01
    • 2016-12-21
    • 2016-02-15
    • 2019-12-01
    • 2011-08-11
    • 2014-08-12
    • 2020-05-05
    相关资源
    最近更新 更多