[英]How to zero array members when my compiler isn't standard conform
My compiler (C++Builder6) syntactically allows array member initialization (at least with zero), but actually it doesn't really do it. 我的编译器(C ++ Builder6)在语法上允许数组成员初始化(至少为零),但实际上并没有真正做到这一点。 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
};
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! 这样您就可以解决您的问题,同时便携性和标准一致性没有任何问题!
You may use fill_n like suggested in: C/C++ initialization of a normal array with one default value 您可以使用fill_n,如: C / C ++初始化具有一个默认值的普通数组
If no fill_n is available, you can always use memset like: 如果没有fill_n可用,您可以始终使用memset,如:
TT() {memset(b, 0, sizeof b);}
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'; TT(){b [0] ='\\ 0'; } }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.