How to zero array members when my compiler isn'

2019-02-24 00:48发布

My compiler (C++Builder6) syntactically allows array member initialization (at least with zero), but actually it doesn't really do it. So the assert in the example given below fails depending from the context.

#include <assert.h>

struct TT {
    char b[8];
    TT(): b() {}
};

void testIt() {
    TT t;
    assert(t.b[7] == 0);
}

Changing the compiler isn't an option at the moment. My question is: what will be the best way to "repair" this flaw with respect to future portability and standard conformance?


Edit: As it turns out, my first example was too short. It missed the point, that the fill level of the array is so essential, that it has to be stored very close to the array, which is: in the same class.

Even if the original problem remains, my actual problem pattern is usually this:

struct TT2 {
    int size;
    char data[8];
    // ... some more elements
    TT2(): size(0), data() {}
    // ... some more methods
};

3条回答
贼婆χ
2楼-- · 2019-02-24 01:27

I think you may use this:

TT() { std::fill(b, b + 8, char()); }

This way you will solve your problem while nothing is wrong with portability and standard conformance!

查看更多
混吃等死
3楼-- · 2019-02-24 01:41

I would like to append previous posts that if you are using a character array as a string then it is enough to write in the constructor

TT() { b[0] = '\0'; }

查看更多
劳资没心,怎么记你
4楼-- · 2019-02-24 01:42

You may use fill_n like suggested in: C/C++ initialization of a normal array with one default value

If no fill_n is available, you can always use memset like:

TT() {memset(b, 0, sizeof b);}
查看更多
登录 后发表回答