gpt4 book ai didi

c - 给数据一个有效的类型算作副作用吗?

转载 作者:太空狗 更新时间:2023-10-29 17:09:12 25 4
gpt4 key购买 nike

假设我有一大块动态分配的数据:

void* allocate (size_t n)
{
void* foo = malloc(n);
...
return foo;
}

我希望将foo 指向的数据用作特殊类型type_t。但我想稍后再做,而不是在分配期间。为了给分配的数据一个有效类型,因此我可以这样做:

void* allocate (size_t n)
{
void* foo = malloc(n);
(void) *(type_t*)foo;
...
return foo
}

根据 C11 6.5/6,此左值访问应生成有效类型 type_t:

For all other accesses to an object having no declared type, the effective type of the object is simply the type of the lvalue used for the access.

然而,行 (void) *(type_t*)foo; 不包含任何副作用,所以编译器应该可以自由地优化它,我不希望它产生任何副作用实际的机器码。

我的问题是:像上面这样的技巧安全吗?给数据一个有效的类型算作副作用吗?或者通过优化代码,编译器是否也会优化有效类型的选择?

也就是说,有了上面的左值访问技巧,如果我现在像这样调用上面的函数:

int* i = allocate(sizeof(int));
*i = something;

这是否会像预期的那样导致严格的别名违规 UB,或者现在是有效类型 int

最佳答案

您引用的标准中的短语清楚地仅说明了有关对象的访问的内容。标准描述的对象有效类型的唯一变化是之前的两个短语,它们清楚地描述了您必须将您想要生效的类型存储到对象中。

6.5/6

If a value is stored into an object having no declared type through an lvalue having a type that is not a character type, then the type of the lvalue becomes the effective type of the object for that access and for subsequent accesses that do not modify the stored value.

关于c - 给数据一个有效的类型算作副作用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51019295/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com