初始化一个常量指针向量

Initialize a constant vector of pointers

我在头文件中有以下 类 旨在为描述嵌入式环境中系统状态的一组指令创建运行时多态性:

class foo
{
public:
  virtual void bar(void) = 0;
  virtual ~foo() {}
};

class derived1 : public foo
{
private:
  int data1;
public:
  void bar(void)
  {
    //implementation 1
  };
  derived1(int d) : data1(d) {}
  ~derived1() {}
};

class derived2 : public foo
{
private:
  int data2;
public:
  void bar(void)
  {
    //implementation 2
  }
  derived2(int d) : data2(d) {}
  ~derived2() {}
};

初始化 const vector<foo*> 类型向量的最佳方法是什么?我目前正在做以下事情:

const std::vector<foo*> v =
{   
  new derived1(a),
  new derived1(b),
  new derived2(c),
  new derived2(d)
};

鉴于 const 限定符,此内存是否仍是动态分配的?它以匿名名称space 存储,供多个州类 使用。因为许多状态 类 共享相同的元素,所以我想定义向量供所有状态选择以保存代码 space。是最适合这种行为的向量吗?

Ps,我不需要担心在任何指针上调用 delete,因为应用程序在所有运行时都需要此信息。

Given the const qualifier, is this memory still dynamically allocated?

是的。 std::vector 内部分配和 const 或没有 const 不会改变这一点。

What is the best way to initialize a vector of type const vector<foo*>?

Best 在这里真的很主观,但通常有两种我喜欢使用的好方法:

  • 用大括号初始化以使用 std::initializer_list;
  • 使用IIFE(立即调用函数表达式);

第一个很明显 - 您已经在使用它了。如果你从未使用过第二个,那么第二个就更诡异了:

const std::vector<int> vec = [someFlag]{
    std::vector<int> non_const;

    non_const.push_back(3);
    if (someFlag) {
        non_const.push_back(-1);
    }
    non_const.push_back(7);

    return non_const;
}(); // <= notice the call - ()

请注意,您最终得到一个 const std::vector,它是 有条件初始化的 (请注意 lambda 中的 if)。诀窍是使用 lambda 和本地非 const 向量将一些值推入其中,然后 return 它。 由于强制复制省略,std::vector 应该只有一个结构。编译器可以自由优化(并且很可能会)任何矢量副本,因此大多数时候只会创建一个 std::vector