Problems with ifdef based inheritance in C++

久未见 提交于 2019-12-11 12:26:22

问题


I was looking at the code of some class I was using, and I came across code like this:

#ifdef SOME_OBSCURE_CONDITION
class A {
#elif 
class A : public B {
#endif

Can there be any problems with such code?

Specifically, suppose file x.cpp includes y.h and z.h. z.h and y.h both include a.h (which defines class A), but additionally y.h defines SOME_OBSCURE_CONDITION. In this case, will two conflicting definitions of A not be present in x.cpp?


回答1:


yes, the two variations simultaneously would violate the ODR (One Definition Rule) and may lead to anything ranging from

  • compile errors
  • link errors
  • undefined behaviour (including but not limited to crashing)

As long as you can make sure that the SOME_OBSCURE_CONDITION define is globally identical (also across partial builds/relinks...) there will not be an issue.




回答2:


If one is using such a code construct then it is the users responsibility to handle the macro correctly.
Can you break it?
Yes, C++ allows you to shoot yourself in the foot, it is up to you to not do so.




回答3:


Impossible to answer in the general case. I'm sure you could find ways to break this, but that's true of pretty much anything.




回答4:


It is your responsibility to guarantee that all translation units see identical type and class definitions. The compiler is not required to produce a diagnostic (and in fact that's not even possible if you want to maintain the benefits of a modular compilation system).

You can produce examples of ill-formed code by giving different TUs different definitions of the same class even without any preprocessor use. Using header files simply requires a certain discipline on your part.




回答5:


The result of this situation is compilation failure or undefined behavior at runtime. If you need to use such class, define this constant in the project settings and not in the code. If you are wrighting this class... well, it is better to think about something else, without using conditional compilation.



来源:https://stackoverflow.com/questions/7646820/problems-with-ifdef-based-inheritance-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!