Has anyone ever had a use for the __COUNTER__ pre-processor macro?

前端 未结 16 1508
有刺的猬
有刺的猬 2020-11-29 00:37

The __COUNTER__ symbol is provided by VC++ and GCC, and gives an increasing non-negative integral value each time it is used.

I\'m interested to learn w

16条回答
  •  攒了一身酷
    2020-11-29 00:52

    I'm interested to learn whether anyone's ever used it,

    Yes, but as you can see from many examples in this Q&A, __LINE__, which is standardized, would also be sufficient in most cases.

    __COUNTER__ is only really necessary in cases where the count must increase by one each time, or it must have continuity over several #include files.

    and whether it's something that would be worth standardising?

    __COUNTER__, unlike __LINE__, is very dangerous because it depends on which header files are included and what order. If two .cpp files (translation units) include a header file that use __COUNTER__, but the header file obtains different count sequences in the different instances, they may use different definitions of the same thing and violate the one-definition rule.

    One-definition rule violations are very difficult to catch and potentially create bugs and security risks. The few use-cases of __COUNTER__ don't really outweigh the downside and lack of scalability.

    Even if you never ship code that uses __COUNTER__, it can be useful when prototyping an enumeration sequence, saving you the trouble of assigning names before the membership is concrete.

提交回复
热议问题