1

I have class Foo with a member variable bar which is a very big array of dynamic_bitset. I would like to make variable bar static for the sake of memory, I would also like it to be const. The value of bar is stored in a predefined file. Where should I put the code for reading the file and initializing bar?

4

3 回答 3

2

MadScienceDreams 的解决方案可能会起作用,但您可以更简单地做到这一点:

在标题中

class A
{
     static const vector<dynamic_bitset> s;
public:
     // ...
};

在实现文件中

vector<dynamic_bitset> LoadBitsets()
{
    //...
    return something;
}

const vector<dynamic_bitset> A::s(LoadBitsets());

应该自动使用移动构造函数。

于 2013-04-19T22:05:54.963 回答
0

我只想从这开始可能是个坏主意,但这就是你在 C++ 中做静态东西的方式:

//A.h
class A
{
private:
    static inline const char* Ptr();
    class static_A
    {
    private:
        char* m_ptr;
        char* AllocateAndReadFile();//SUPER UNSAFE AND BAD CODE (Make sure it is SUPER hidden from end users, put warning comments all over the place
    public:
        static_A();
        ~static_A();
        friend const char* A::Ptr(void);
    };
    static static_A a_init;


public:
    A();
};
//i'd probably put this indirection function here, in definition so its inlined
inline const char* A::Ptr()
{
    return a_init.m_ptr;
}

//A.cpp
A::static_A A::a_init = A::static_A();

A::static_A::static_A() : m_ptr(AllocateAndReadFile())
{
}
A::static_A::~static_A()
{
    delete [] m_ptr;
}
char* A::static_A::AllocateAndReadFile()
{
    char* foo = new char[1000000];
    memset(foo,0,sizeof(char)*1000000);
    //put your read function here...note that because read must be static, 
    //the file location must be hard coded, so I don't like this solution at all
    FILE* fid = fopen("C:/stuff.txt","r");
    size_t readchars = fread(foo,sizeof(char),1000000,fid);
    return foo;
}

A::A()
{
    char buff[100];
    memcpy(buff,Ptr(),99);
    printf(buff);
}

您还可以使 a_init 成为一个不透明的指针,并将 A::static_A 的整个定义放在A.cpp... 在这种情况下可能会更好。

于 2013-04-19T21:41:50.327 回答
-3

是不可能的。

const关键字是在编译时设置的值,但是你想从文件中读取是运行时操作,所以不可能。

定义bar为 static bot 而不是 const,注意不要更改它。

于 2013-04-19T21:50:32.410 回答