开发者

Simple C++ syntax question about colon

开发者 https://www.devze.com 2022-12-19 13:59 出处:网络
I just saw a code snippet with a piece of syntax that I have never seen before. What does bool start : 1; mean? I found it inside a class definition开发者_StackOverflow中文版 in a header file.struct r

I just saw a code snippet with a piece of syntax that I have never seen before. What does bool start : 1; mean? I found it inside a class definition开发者_StackOverflow中文版 in a header file.


struct record {
    char *name;
    int refcount : 4;
    unsigned dirty : 1;
};

Those are bit-fields; the number gives the exact size of the field, in bits. (See any complete book on C for the details.) Bit-fields can be used to save space in structures having several binary flags or other small fields, and they can also be used in an attempt to conform to externally-imposed storage layouts. (Their success at the latter task is mitigated by the fact that bit-fields are assigned left-to-right on some machines and right-to-left on others).

Note that the colon notation for specifying the size of a field in bits is only valid in structures (and in unions); you cannot use this mechanism to specify the size of arbitrary variables.

  • References: K&R1 Sec. 6.7 pp. 136-8
  • K&R2 Sec. 6.9 pp. 149-50
  • ISO Sec. 6.5.2.1
  • H&S Sec. 5.6.5 pp. 136-8


it's a bitfield. : 1 means one bit is used. see for example http://msdn.microsoft.com/en-us/library/ewwyfdbe(VS.71).aspx


It means that start is 1 bit wide, as opposed to the normal bool which is 1 byte long. You can pack multiple smaller variables into a larger variable and the compiler will generate all the and/or code necessary to read/write it for you. You will take a (noticeable) performance hit, but, if used right, you'll use a lot less memory.


See the Wikipedia entry about Bit Fields. It tells the compiler how many bits the structure member should occupy.


It makes the member start into a bit-field, with 1 bit of space reserved.

It's only valid for struct/class members, you can't have a bit-field variable.


This is the syntax for bit fields

Essentially, you define a field in a struct to have only a few bits of a full byte or short or int.
Several bit fields may share the same int so this method can be used as a clever way to avoid some bit manipulations in constructing values.


This is the syntax for describing bit fields. This is a way of packing more information into a smaller amount of storage. Whereas normally a bool would take at least a byte (probably more) to represent, by using bit fields, you can combine several bools into one byte with a simple syntax.

Be careful though. As one of lesser-known areas of the language, you may run into corner cases when using them. For example, the data structures thus produced are probably not portable between processor types.


It's a bit-field. But I've never tried making bit-fields on boolean.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号