Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "there is no smaller array object that satisfies these constraints" mean?

The draft n4659 for C++17 describes the general principes of the language in chapter 4. In chapter 4.5, The C++ object model [intro.object], I cannot understand the meaning of one sentence (emphasize mine)

3 If a complete object is created (8.3.4) in storage associated with another object e of type “array of N unsigned char” or of type “array of N std::byte” (21.2.1), that array provides storage for the created object if:
(3.1) — the lifetime of e has begun and not ended, and
(3.2) — the storage for the new object fits entirely within e, and
(3.3) — there is no smaller array object that satisfies these constraints.

while examples show that an array can provide storage for elements much shorter than the array:

struct A { unsigned char a[32]; };
struct B { unsigned char b[16]; };
A a;
B *b = new (a.a + 8) B; // a.a provides storage for *b
int *p = new (b->b + 4) int; // b->b provides storage for *p

here *p uses only 4 bytes (assuming sizeof(int) is 4) in a 16 bytes array. So, what is the meaning of 3.3?

like image 524
Serge Ballesta Avatar asked Jan 03 '18 10:01

Serge Ballesta


1 Answers

The meaning if 3.3 is to differentiate a[32] from b[16]. The former doesn't provide storage for *p because the latter does. It identifies the smallest unique array object that provides the region of storage where the object resides.

Without 3.3 the definition would be transitive. a[32] would provide storage for *p because it ultimately provides storage for b[16].


Regarding *p using 4 bytes. It's important to note that the region [b->b + 4, b->b +8), while being the storage where *p resides, is not the array object providing the storage (that region isn't an array object at all). That smallest array object would be b->b.

like image 154
StoryTeller - Unslander Monica Avatar answered Nov 06 '22 03:11

StoryTeller - Unslander Monica