gpt4 book ai didi

具有指针的结构的 const 正确性

转载 作者:太空狗 更新时间:2023-10-29 16:52:45 26 4
gpt4 key购买 nike

我有一个包含一些指针的结构。我希望这些值是不可修改的。但是简单地写 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
}

谁能给我指出正确的方向。

编辑:

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

最佳答案

您可以通过定义一个常量点类型和一个可变点类型,然后使用一个透明的 union ,在不进行类型转换的情况下做到这一点:

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;

然后,您使用 point 或 const_point 类型(绝不是 mutable_point 类型)声明您的函数参数。

point 类型对象将透明地转换为 const_point 类型,但反之则不然。这使您具有更高程度的类型安全性。

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

请注意,我检查的最新版本的 C++ 不支持透明 union (不确定最新的 C++ 标准),因此您可能会遇到可移植性问题。

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

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

关于具有指针的结构的 const 正确性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13181546/

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