|
|
|
|
|
by jpegqs
1459 days ago
|
|
Explanation: 1. There are no data members inside X, in this case the size of the structure is 1 byte. 2. main() does nothing. 3. *x = new X[100]() - this requests a new array of 100 elements of type X, at a stage before main() is called. 4. The new[] operator is overloaded in the class, this operator must return the address for the requested array. It returns the address of the empty string object plus 1. 5. For each of the 100 elements, the X() constructor is called, the "this" address for those elements will be the value returned by new[] plus an index from 0 to 99. The X() constructor converts this to a number from 1 to 100 by subtracting the address of the empty string. This is the only UB here, but it works in all major modern compilers since they combine the same strings into one instance. |
|
That's debateable.
1. new[] doesn't return a pointer that is suitable for storage for the objects. Yes the objects are empty (only contain padding), but that doesn't absolve from UB.
2. "" is used at two places, assuming that they refer to the same const char array. This is optimization is allowed, commonly implemented, but not guaranteed.
3. An empty struct having 1 byte size is also implementation defined, although common ABIs specify this. It also wouldn't make sense to implement it differently.