给数据一个有效的类型是否算作副作用? [英] Does giving data an effective type count as a side-effect?

查看:89
本文介绍了给数据一个有效的类型是否算作副作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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:

对于没有声明类型的对象的所有其他访问,该对象的有效类型就是用于访问的左值的类型.

但是,(void) *(type_t*)foo;行没有任何副作用,因此编译器应该可以自由地对其进行优化,并且我不希望它生成任何实际的机器代码.

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

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

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

这是否会导致严格的混叠违规UB,如预期的那样,或者有效类型现在是int?

解决方案

您明确引用的标准中的短语仅表示有关对象的访问的信息.标准描述的对象的有效类型的唯一变化是在此之前的两个短语,它们清楚地描述了您必须以想要使之有效的类型存储到对象中. /p>

6.5/6

如果一个值通过一个值存储到一个没有声明类型的对象中 具有非字符类型的左值,则左值的类型变为 该访问以及未修改的后续访问的对象的有效类型 存储的值.

Suppose I have a chunk of dynamically allocated data:

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

I wish to use the data pointed at by foo as a special type, type_t. But I want to do this later, and not during allocation. In order to give the allocated data an effective type, I can therefore do something like:

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

As per C11 6.5/6, this lvalue access should make the effective type 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.

However, the line (void) *(type_t*)foo; contains no side effects, so the compiler should be free to optimize it away, and I wouldn't expect it to generate any actual machine code.

My question is: are tricks like the above safe? Does giving the data an effective type count as a side-effect? Or by optimizing away the code, will the compiler also optimize away the choice of effective type?

That is, with the above lvalue access trick, if I now call the above function like this:

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

Does this cause strict aliasing violation UB as expected, or is the effective type now int?

解决方案

The phrase from the standard that you are citing clearly only states something about the access to the object. The only changes to the effective type of the object that the standard describes are the two phrases before that, that clearly describe that you have to store into the object with the type that you want to make effective.

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.

这篇关于给数据一个有效的类型是否算作副作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆