JM:I have a dream,期待和你一起去实现!
原文及译文
JM
网友:Ton van den Heuvel

        给定以下代码:char * p = static_cast(malloc(sizeof(T)* 32)); T * t1 = new(p)T; p = sizeof(T); T * t2 = new(p)T; ......

推荐:想去Google查资料?(你懂的)想建站?想测试?想挂机?想折腾?想要高性价比的服务器?点我!!


在以下情况下是否可以分配错位对象?(Is it possible to allocate misaligned objects in the following case?)

假设我们有一些有效的类型T.给定下面的代码:

char* p = static_cast<char*>(malloc(sizeof(T) * 32));
T* t1 = new (p) T;
p += sizeof(T);
T* t2 = new (p) T;
...

现在是否可以根据其对齐限制不正确地对齐t2?


Suppose we have some valid type T. Given the following code:

char* p = static_cast<char*>(malloc(sizeof(T) * 32));
T* t1 = new (p) T;
p += sizeof(T);
T* t2 = new (p) T;
...

Is it now possible for t2 to not be aligned correctly according to its alignment restrictions?


解决方案(由网友user2079303提供)

取决于T是什么。这些保证与将指针直接存储到T *中相同。如果指针P与N字节边界对齐,则P N也与N对齐。另外,大小必须是对齐的倍数。 malloc的内存保证对齐max_align_t。

如果该指针是超对齐类型,即对齐要求高于max_align_t的类型,则该指针不能保证与T对齐。


Depends on what T is. The guarantees are same as if you had stored the pointer directly into T*. If a pointer P is aligned to N byte boundary, then P+N is also aligned to N. Also, the size must be a multiple of the alignment. malloc'd memory is guaranteed to be aligned up to the alignment of max_align_t.

The pointer is not guaranteed to be aligned for {mark2} if it is an over aligned type i.e. a type with higher alignment requirement than {mark2}.


推荐:想去Google查资料?(你懂的)想建站?想测试?想挂机?想折腾?想要高性价比的服务器?点我!!


关于站长

JMJavaMethod的缩写,苦逼码农一个,一直想有番作为,奈何人老力衰,只能四处膜拜大佬以获得动力。已经从单机、局域网、互联网、混到了移动互联网,未来希望能在AI世界里继续混下去。这辈子有个终极目标:财务自由,心灵自由。

近期公告

一个人苦逼开发多日,网站终于正式上线,求关注!!! 一个人苦逼多日,终于正式上线,求关注!!!

找他  
猜你喜欢
想建站?想测试?
想挂机?想折腾?
想去Google查资料?(你懂的)
想要高性价比的服务器?
搬瓦工VPS - 性价最高的美国便宜VPS主机
友情链接

冀ICP备17016304号 版权所有 © JavaMethod.com All Rights Reserved,Theme by 拼图