0

Let's take this example:

struct Foo {
   int &i;
   Foo(int &i) : i(i) {}
  private:
   int a, b, c, d;
};

The internal a..d attributes are not used. Is the compiler allowed to remove them from the objects?

Also is the reference also removed during link?

I am wondering if the compiler is allowed to remove a, b, c, d from the object since it is not used. Also if the intermediate instance can be removed from the

nowox
  • 25,978
  • 39
  • 143
  • 293
  • 1
    It would have to *prove* they aren't ever used, which might be difficult since any code with access to `sizeof(Foo)` could be affected if member-variables were optimized out and `sizeof(Foo)` got smaller. – Jeremy Friesner May 01 '23 at 19:21
  • The compiler has the as-if rule. As long as it doesn't change the observable behavior it can do whatever it wants. That said, no compiler I have seen has tried to do such an optimization. This does sound like an XY problem. Are you doing something that would rely on this? – NathanOliver May 01 '23 at 19:27
  • 1
    Near duplicate of [Does an unused member variable take up memory?](https://stackoverflow.com/q/55060820) - the as-if rule does apply, but if you do anything where the size matters (like allocate an array), it will use the real size. Optimization level doesn't change the ABI, so you can link multiple `.o` files build with different optimization options. Thus, optimization level can't change object sizes except when partly optimizing away local vars that don't "escape". – Peter Cordes May 01 '23 at 19:31
  • IMHO, you should have a parent class with the variables that are in use, and a child class with the variables that may not be in use. – Thomas Matthews May 01 '23 at 20:08

1 Answers1

2

The compiler cannot change the layout based on optimization levels.

To test this, simply output the size the struct using different compilers settings:

cout << sizeof(Foo) << endl;
RandomBits
  • 4,194
  • 1
  • 17
  • 30