是否铸有指针已从size_t来回或uintptr_t形式打破严格走样? [英] Does casting a pointer back and forth from size_t or uintptr_t break strict aliasing?

查看:209
本文介绍了是否铸有指针已从size_t来回或uintptr_t形式打破严格走样?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我提议更改其公共API目前看起来是这样的一个库:

I'm proposing a change to a library whose public API currently looks like this:

typedef size_t enh;  /* handle */

int en_open(enh *handle)
{
    struct internal *e = malloc(...);
    *handle = (enh)e;
    return 0;
}

int en_start(enh handle)
{
    struct internal *e = (struct internal*)handle;
    return do_something(e);
}

这是否使用,铸造来回为size_t 打破严格走样?

有关记录,我提议结构内部的公共API中,如图上的这个Programmers.SE问题差不多code

For the record, I'm proposing a typical opaque forward declaration of struct internal in the public API, as shown on this Programmers.SE question about the same code.

推荐答案

混叠是大约两个不同类型的指针被用来访问同一字节。这是不是在你的code的情况。当您访问数据成员手柄后面,你总是通过键入内部结构* 的指针做到这一点。所以在这里没有坏处。

Aliasing is about two pointers of different type being used to access the same bytes. This is not the case in your code. When you access the data members behind the handle, you always do it via a pointer of type struct internal*. So no harm here.

在code,唯一值得商榷的是,您正在使用为size_t 来传递指针。据我所知,该标准并不能保证你可以放心地投出指针为size_t 和背部,尽管任何理智的实施,将允许它。正确的整数类型的选择是 uintptr_t形式,但你甚至不需要是:

The only questionable thing in your code is, that you are using size_t to pass the pointer. Afaik, the standard does not guarantee that you can safely cast a pointer to size_t and back, even though any sane implementation will allow it. The correct integer type choice would be uintptr_t, but you don't even need that:

我想,你应该只使用一个不透明的指针的接口。一,即,只是把声明

I think, you should just use an opaque pointer in the interface. I. e., just put the declaration

typedef struct internal internal;

到自己的公用头,并保持相应的

into your public header and keep the corresponding

struct internal {
    ...
}

私有(更换内部有一个合理的公共名字,当然)。公共功能可后来干脆被声明为:

private (replacing internal with a sensible public name, of course). The public functions can then simply be declared as:

int en_open(internal** outHandle);
int en_close(internal* handle);

这样的话,你在客户端code完美的类型检查,并避免任何类型转换的需要。

That way, you get perfect type checking in the client code, and avoid the need for any casts.

这篇关于是否铸有指针已从size_t来回或uintptr_t形式打破严格走样?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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