可以GCC提醒我有关修改C99一个const结构的领域? [英] Can GCC warn me about modifying the fields of a const struct in C99?

查看:106
本文介绍了可以GCC提醒我有关修改C99一个const结构的领域?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我偶然发现了一个小问题,而试图让常量,正确的code。

I stumbled upon a small issue while trying to make const-correct code.

我也喜欢写一个函数,它接受一个指向const结构,告诉编译器请告诉我,如果我修改结构,因为我真的不想。

I would have liked to write a function that takes a pointer to a const struct, to tell to the compiler "please tell me if I am modifying the struct, because I really do not want to".

这突然来到我的脑海里,编译器将允许我这样做:

It suddenly came to my mind that the compiler will allow me to do this:

struct A
{
    char *ptrChar;
};

void f(const struct A *ptrA)
{
    ptrA->ptrChar[0] = 'A'; // NOT DESIRED!!
}

这是可以理解的,因为究竟是const为指针本身,而不是它指向的类型。我想为编译器告诉我,我做的事情我不想做的,不过,如果这甚至有可能。

Which is understandable, because what actually is const is the pointer itself, but not the type it points to. I would like for the compiler to tell me that I'm doing something I do not want to do, though, if that is even possible.

我用gcc作为我的编译器。虽然我知道,上面的code应该是合法的,我还是检查它是否会反正发出警告,但无疾而终。我的命令行是:

I used gcc as my compiler. Although I know that the code above should be legal, I still checked if it would issue a warning anyways, but nothing came. My command line was:

gcc -std=c99 -Wall -Wextra -pedantic test.c

是否有可能解决这个问题呢?

Is it possible to get around this issue?

推荐答案

设计解决这个自己的方式的一种方式,如果需要的话,就是用两种不同类型相同的对象:一个读/写类型和一个只读类型。

A way to design your way around this, if needed, is to use two different types for the same object: one read/write type and one read-only type.

typedef struct
{
  char *ptrChar;
} A_rw;

typedef struct
{
  const char* ptrChar;
} A_ro;


typedef union
{
  A_rw rw;
  A_ro ro;  
} A;

如果函数需要修改的对象,它需要的读写型为参数,否则它需要只读类型

If a function needs to modify the object, it takes the read-write type as parameter, otherwise it takes the read-only type.

void modify (A_rw* a)
{
  a->ptrChar[0] = 'A';
}

void print (const A_ro* a)
{
  puts(a->ptrChar);
}

要pretty了来电界面,使它保持一致,可以使用包装功能的公共接口的ADT:

To pretty up the caller interface and make it consistent, you can use wrapper functions as the public interface to your ADT:

inline void A_modify (A* a)
{
  modify(&a->rw);
}

inline void A_print (const A* a)
{
  print(&a->ro);
}

通过这种方法, A 现在可以实现为不透明的类型,隐藏呼叫者的执行情况。

With this method, A can now be implemented as opaque type, to hide the implementation for the caller.

这篇关于可以GCC提醒我有关修改C99一个const结构的领域?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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