0

我对静态变量或其他方式有疑问。

我有一个大师班,PatternMatcher。我有几个派生单位,具体取决于使用的匹配器。现在每个子类都需要存储一个浮点向量,但在每个类中它是常量。该向量的数据是在初始化期间读取的,最大为 1GB(我拥有的最小的是 1MB,最大的是 1GB)。目前,当我有两个 Matcher_A 实例时,它将分配两倍的内存。我事先不知道要使用哪些匹配器(每次运行将是三个匹配器,您可以多次使用同一个匹配器)。我宁愿不在运行时检查所需的匹配器是否已经在某处初始化,因为这将需要为我所做的每次更改添加额外的代码。

目前我分配了3个匹配器

PatternMatcher* a = new PMMatcherA();
PatternMatcher* b = new PMMatcherB();
PatternMatcher* c = new PMMatcherC();

,但由于它们是用户选择的,因此例如 A 和 C 可能相同。当我通过 运行检查时typeid(a).name();,它会给我 PatternMatcher 作为结果,不管我以前用什么类启动。PatternMatcher 基本上是一个纯粹的虚拟类。

我一直认为静态意味着一个变量在不同的分配中是恒定的,但是当我将我的向量定义为静态时,我会得到一个链接器解析错误。在较早的迭代中,我将这些向量设为全局,但希望将它们本地化到它们的类中。

我需要使用哪些关键字才能使初始化时的向量可用于下一次初始化?一个简单的检查向量大小是否大于 0 就足够了,但是每个对象都使用自己的向量。

4

3 回答 3

1

Yes, static is what you need. You can use it like this:

class MyClass
{
private:
    static std::vector< float > data_;
};

std::vector< float > MyClass::data_;

Please note that in the class itself you only declare static variables. But you also need to define them outside of the class exactly once. That's why we have the line std::vector< float > MyClass::data_;, if you omit that, you will have linker errors.

After this, every object of MyClass class will share the same data_ vector.

You can operate it either from any object of the class:

MyClass a;
a.data_.push_back(0);

or through the class name:

MyClass::data_.push_back(0);

于 2012-08-06T09:38:38.480 回答
1

static keyword is a way to go - that would store exactly one copy of a member for the whole class. What you were missing is an actual declaration of such static in a compilation module so that the linker can use it. For instance:

header file foo.h:

struct Foo {
  static int s_int;
}

source file foo.cpp:

#include "foo.h"
int Foo::s_int; // optionally =0 for initialization

The second part is vital as this will allocate a memory space for the object to be used as a static member.

Keep in mind, though, that:

  • static members will all be initialized before the main(), which means your 1GB of data will be read regardless of whether anyone ever uses that particular class
  • You can work around the abovementioned issue, but then you will have to be checking if the data load and initialization has happened during run-time

There's another option for you, however. If you store your floats "as-is" (i.e. 32 bits per each, in binary format) you can just simply "map" the files into memory spaces and access them as if they were already loaded - the OS will take care of loading appropriate 4K pages into RAM when needed.

Read more about mmap at http://en.wikipedia.org/wiki/Mmap

于 2012-08-06T09:39:00.620 回答
1

当我将向量定义为静态时,我会收到链接器解析错误。

这是因为您声明了静态变量(在您的头文件中),但您从未在您的一个实现文件(.cpp)中显式初始化它。

例如:

//AClass.h 
class AClass
{
    private:
    static std::vector<int> static_vector;

};

并在 .cpp 实现文件中:

std::vector<int> AClass::static_vector;
于 2012-08-06T09:40:29.617 回答