简体   繁体   English

如何从字符串文字初始化无符号字符数组?

[英]How to initialize an unsigned char array from a string literal?

I have a struct with an unsigned char[16] field that I'd like to initialize to zeros. 我有一个带有unsigned char[16]字段的结构,我想将其初始化为零。 The following (strongly simplified) code compiles fine with clang (OS X): 以下(经过简化的)代码可以使用clang(OS X)正常编译:

struct GUID {
    unsigned char bytes[16];
    GUID() : bytes("\0\0\0\0""\0\0\0\0""\0\0\0\0""\0\0\0") {};
}

Note I use 15 \\0 s because the 16th is the zero terminator of the string literal, and clang complains if you initialize a string with too many bytes. 注意我使用15 \\0 s,因为16th是字符串文字的零终止符,如果初始化的字节数过多,clang会抱怨。

Now, when I try to compile with GCC 4.5.3 (cygwin), I get: 现在,当我尝试使用GCC 4.5.3(cygwin)进行编译时,我得到:

error: incompatible types in assignment of 'const char [16]' to 'unsigned char [16]'

Why doesn't it work, and how can I make it work? 为什么它不起作用,我如何使它起作用? (I could obviously loop through the array in the constructor, but I'd like to use the initialization list if possible, and I'd like to understand why it works in one compiler, but not the other.) (显然,我可以遍历构造函数中的数组,但我想尽可能使用初始化列表,并且我想了解为什么它在一个编译器中起作用,而在另一个编译器中不起作用。)

A simple bytes() should be sufficient in this case. 在这种情况下,一个简单的bytes()就足够了。 You could also consider bytes { 0,0,0,0.... } . 您还可以考虑bytes { 0,0,0,0.... }

Also, use std::array , not T[] . 另外,请使用std::array ,而不要使用T[] Only fools use T[] when they could use std::array . 只有傻瓜可以使用std::array时才使用T[]

Since we're dealing with POD its sufficient to explicitly construct bytes, which will result in the corresponding memory being 'zeroed': 由于我们正在处理POD,因此足以显式构造字节,这将导致相应的内存被“清零”:

struct GUID 
{
    unsigned char bytes[16];
    GUID() : bytes(){}
};

It's probably worth noting that if you didn't explicitly construct bytes in the initialization list, it would be left uninitialized 可能值得注意的是,如果您未在初始化列表中显式构造字节,则将其保持未初始化状态。

struct GUID 
{
    unsigned char bytes[16];
    GUID(){};
};

If the member variable were not a POD but instead a member object then instead of being left uninitialized it would call its default constructor. 如果成员变量不是POD而是一个成员对象,那么它将被调用其默认构造函数,而不是未初始化。

在GUID构造函数中,您可以使用memset(bytes,0,sizeof(bytes));

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

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