简体   繁体   中英

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.

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. 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. 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?

Note: Base classes B and C are totally independent and have no dependency on each other

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.

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.

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]. M is less than you used in the code. I also have this trouble today. I defined bool mMyArray[6];

However, in my code, I uses somewhere mMyArray[7] = false;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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