const指针结构的正确性

mon*_*ing 9 c constants const-correctness

我有一个包含一些指针的结构.我希望这些价值不可修改.但是简单地编写const infront并不会使结构成员不可靠

typedef struct{
  int *x;
  int *y;
}point;

void get(const  point *p,int x, int y){
  p->x[0]=x;//<- this should not be allowed
  p->y[0]=y;//<- this should not be allowed
}
Run Code Online (Sandbox Code Playgroud)

有人能指出我正确的方向.

编辑:

因此,似乎没有简单的方法来使用函数原型来告诉属于该结构的所有内容都应该是不可修改的

Dro*_*com 9

您可以通过定义const点类型和可变点类型而无需进行类型转换,然后使用透明联合:

typedef struct{
    const int *  x;
    const int *  y;
} const_point;

typedef struct{
    int *  x;
    int *  y;
} mutable_point;

typedef union __attribute__((__transparent_union__)) {
    const_point cpoint;
    mutable_point point;
} point;
Run Code Online (Sandbox Code Playgroud)

然后,使用point或const_point类型声明函数参数(从不使用mutable_point类型).

点类型对象将透明地转换为const_point类型,但不是相反的.这使您可以获得更高程度的类型安全性.

请参阅此处获取gcc中的示例:http://toves.freeshell.org/xueg/

请注意,我检查的C++的最新版本不支持透明联合(不确定最新的C++标准),因此您可以预期可移植性问题.

它还可以使代码更难以阅读和维护,特别是如果您有更复杂的结构.例如:你可以有点类型,其中x或y是const,或者你可能需要将你的点结构嵌入到另一个结构中,例如矩形,你可能需要根据它们的常量为多个类型定义多个结构.

总而言之,我不确定它总是值得额外的麻烦.


AnT*_*AnT 5

如果我正确理解您的问题,您希望将整个结构对象的常量自动传播到该结构成员指向的对象。即,如果 struct 对象不是 const,则数组应该是可修改的,而如果 struct 对象是 const,则数组不应该是可修改的。

如果是这样,那么不幸的是,这在 C 语言中是无法实现的。

在C++中,可以通过强制用户使用访问器成员函数来访问数据成员(而不是直接访问数据成员)来完成。但在 C 语言中这是根本不可能完成的。


Des*_*Ice 2

解释你在写作时需要建立的内容

point str;

point *p=&str;
Run Code Online (Sandbox Code Playgroud)

这里p 是指向 str 的指针,其类型为point

当你将它声明为const时,就意味着p是一个常量指针。这并不限制该结构可能包含的指针。

如果您希望将其const应用于结构内部,则必须将结构内部的指针也定义为 const

typedef struct{
   const int *  x;
   const int *  y;
}point;
Run Code Online (Sandbox Code Playgroud)

再次强调我的观点,将参数声明为

    void get(point * const  p,int x, int y) 
   //Constant Pointer ( *to prevent p from pointing to anything else*)

    //    AND

   //Make the pointers inside point structure constant
   //( *to prevent the int pointers x & y from pointing to anything else*)
Run Code Online (Sandbox Code Playgroud)

如果它指向的结构也是 const use

      void get(const point * const p, int x, int y)
     //Constant Pointer to constant structure 
Run Code Online (Sandbox Code Playgroud)