简体   繁体   English

C ++ const静态成员数组初始化

[英]C++ const static member array initialization

I have class Foo with a member variable bar which is a very big array of dynamic_bitset. 我有一个带有成员变量栏的Foo类,它是一个很大的dynamic_bitset数组。 I would like to make variable bar static for the sake of memory, I would also like it to be const. 为了存储起见,我想使可变条成为静态,我也希望它是const。 The value of bar is stored in a predefined file. bar的值存储在预定义文件中。 Where should I put the code for reading the file and initializing bar? 我应该在哪里放置用于读取文件和初始化栏的代码?

MadScienceDreams's solution will probably work, but you can do this much more simply: MadScienceDreams的解决方案可能会起作用,但是您可以更简单地做到这一点:

In header 在标题中

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

In implementation file 在执行文件中

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

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

The move constructor should get used automatically. move构造函数应自动使用。

I Just want to start with this is probably a bad idea, but this is how you do static stuff in c++: 我只是想从这开始可能不是一个好主意,但这是您在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);
}

You could also make a_init an opaque pointer and put the entire definition of A::static_A in A.cpp ...that might be better in this case. 您还可以使a_init为不透明的指针,并将A :: static_A的整个定义放在A.cpp ……在这种情况下可能会更好。

It is impossible. 是不可能的。

const keywords means set value at compile time, but you want to read from file which is a runtime operation, so it is impossible. const关键字表示在编译时设置值,但是您想从文件中读取它是运行时操作,因此这是不可能的。

Define bar as static bot not const, be careful to don't change it. bar定义为静态bot而不是const,请注意不要对其进行更改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM