简体   繁体   English

成员顺序,派生顺序有关系吗?

[英]Order of members, order of derivation matters?

Sometimes I have come across this issue that whenever I change the order of members, order of derivation in my C++ class the issue gets solved, crash gets fixed. 有时我碰到过这个问题,每当我更改成员的顺序,C ++类中的派生顺序时,问题都会得到解决,崩溃会得到解决。

Recently I moved the position of a private member variable from a lower location to the top of my class and the error got fixed 最近,我将私有成员变量的位置从班级的较低位置移到了班级顶部,并且错误已得到解决。

Another time I had a class A:public B, public C. The moment I changed this to class A:public C, public B the crashing code started working. 还有一次我有A类:公共B,公共C。当我将其更改为A类:公共C,公共B时,崩溃代码开始起作用。 C is class containing virtual methods and in the former case class A was not finding the method overriden in C but in the later it was able to find. C是包含虚拟方法的类,在前一种情况下,类A找不到C中重写的方法,但在后来的情况下,它可以找到。 Is this due to virtual pointer corruption? 这是由于虚拟指针损坏吗? If so what has it got to do with order of members? 如果是这样,那与会员顺序有什么关系? I know the memory layout changes when we change order of members but how do we debug such sort of issues because in VS2008 I could not find any indication as to why the crash was happening? 我知道更改成员顺序时内存布局会发生变化,但是我们如何调试此类问题,因为在VS2008中我找不到任何有关崩溃发生原因的指示?

Note: Base classes B and C are totally independent and have no dependency on each other 注意:基类B和C完全独立,彼此之间没有依赖关系

Base classes and member objects are initialized in declaration order, not the order of the initializer list. 基类和成员对象按声明顺序(而不是初始化列表的顺序)初始化。

If one of the bases receives a pointer to another base object and does anything more than just store the pointer for later use in its constructor, then the ctor will access an object that has not yet been constructed. 如果其中一个基址接收到指向另一个基址对象的指针,并且除了将指针存储以供以后在其构造函数中使用外,其他任何操作,那么ctor将访问尚未构造的对象。

Using /W3 warning level under MSVC/VS should give warnings both when this is passed to a base ctor pointing to a part of the object that is not initialized yet, and when the initializer list was shuffled to match declaration order. 在MSVC / VS下使用/W3警告级别,应在this其传递到指向尚未初始化的对象的一部分的基本ctor以及将初始值设定项列表改组以匹配声明顺序时发出警告。

Possibilities: 可能性:

  • You didn't recompile all your source, so your headers got out of sync; 您没有重新编译所有源代码,因此标头不同步。
  • You have some epic Undefined Behaviour somewhere that's ruining everything. 您在某个地方毁灭了所有史诗般的未定义行为。

Steps to debug: 调试步骤:

  • Run through a static analysis tool 通过静态分析工具运行
  • Full rebuild in debug mode 在调试模式下完全重建
  • Run through a debugger 通过调试器运行
  • Run through a dynamic analysis tool 通过动态分析工具运行

It could be that you defined an array : int A[M]. 可能是您定义了一个数组:int A [M]。 M is less than you used in the code. M小于您在代码中使用的M。 I also have this trouble today. 我今天也有这个麻烦。 I defined bool mMyArray[6]; 我定义了布尔mMyArray [6];

However, in my code, I uses somewhere mMyArray[7] = false; 但是,在我的代码中,我在某处使用了mMyArray [7] = false;。

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

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