How to Fix Weird C++ Codes that Assume the Relative Ordering of Class Members

94 Views Asked by At

I need to modify the ordering of my C++ class members. For example:

class B {
public:
int i;
int j;
int k;
...
};

becomes

class B {
public:
int j;
int k;
int i;
...
};

The problem is there are weird codes in my large code bases that depend on relative location of the class members. For example some functions would assume address of member j is smaller than that of member k.

Is there any CASE tool that can help me to identify any code that read the address of a class member?

1

There are 1 best solutions below

4
On

I am not aware of any tool that solve your problem, but I would define a class which supports all operators for int type and which overloads ampersand operator so that the result of the operator cannot be casted to a pointer. Then I'd use this class instead of int in your class member definitions and look at places where compiler gives errors.

Something like

class IntWrapper {
 public:
  IntWrapper() { }
  IntWrapper(const int x) { }         // don't care about implementation as we 
  operator int() const { return 0; }  // want compile-time errors only
  IntWrapper& operator ++() { return *this; }
  IntWrapper& operator ++(int) { return *this; }

  ...
  void operator &() const { } // make it void so it would cause compiler error
};

And then:

class B {
 public:
  IntWrapper i;
  IntWrapper j;
  IntWrapper k;
 ...
};

This will not help against using boost::addressof function or some dirty reinterpret_cast of a reference, but addressof is probably never used at all in your project, as well as the reinterpret_cast<char&> trick (who would use it for plain integers?).

You should also care about taking an address of the whole object of B class.