代码之家  ›  专栏  ›  技术社区  ›  Sasha

C: void*作为句柄,失去const表达能力

  •  0
  • Sasha  · 技术社区  · 2 年前

    我尝试考虑一种API策略,在头文件中

    typedef struct {...} type_t;
    extern void func(const type_t* instance);
    

    我有

    typedef void* type_t_handle;
    extern void func(const type_t_handle instance);
    

    但我现在发现,在我有选择之前

    const type_t* const x; // (1)
    const type_t* x;       // (2)
    type_t* const x;       // (3)
    

    我现在只有选项(3)(我看了一次那篇文章 const type_t_handle const x; 导致“重复的const声明说明符”警告)。换句话说 typedef 似乎“束缚”了 * 和基类型,我们不能再“挤压”介于两者之间的常量。。。

    这意味着 const 在参数中 const type_t_handle instance 我认为这是无用的——它不会导致“传递参数…丢弃常量限定符”——类型警告,它会提醒不修改的意图。。。

    有什么解决办法吗?

    1 回复  |  直到 2 年前
        1
  •  1
  •   dbush    2 年前

    你说得对 typedef 将指针绑定到基类型,因此不能使指针指向类型 const

    你需要做一个单独的 类型定义 对于 const 合格版本。

    typedef void* type_t_handle;
    typedef const void* const_type_t_handle;
    

    附带说明,而不是使用 void * 对于API使用的类型,请改用不透明结构,即在头文件中声明但在实现文件中定义的结构。

    typedef struct xyz type_t;
    extern void func(const type_t* instance);
    

    这提供了比使用普通类型更好的类型安全性 无效*