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

谁都会走 提交于 2020-06-10 08:43:42

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/48075112/what-does-there-is-no-smaller-array-object-that-satisfies-these-constraints-me

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!