简体   繁体   English

function 参数中的 const *const 指针

[英]const *const pointers in function parameters

I have a question about best practices involving pointers in function parameters and whether they should be specified as *const or const *const .我对涉及 function 参数中的指针的最佳实践以及是否应将它们指定为*constconst *const有疑问。 I know there are varying opinions on use, or excessive use, of const , but at least some use is a good way to catch accidental mistakes.我知道对于const的使用或过度使用有不同的看法,但至少有一些使用是捕捉意外错误的好方法。

Say you have the following function, which is part of the implementation of a queue based on a linked list:假设您有以下 function,它是基于链表的队列实现的一部分:

void enqueue(struct queue *q, void *data)
{
    struct queue_node *item = malloc(sizeof(*item));
    item->data = data;

    [add node to linked list, specifics are not relevant here]
}

struct queue_node is defined as struct queue_node定义为

struct queue_node {
        struct queue_node *next;
        void *data;
};

data is not meant to be modified in this function, so it seems like a good idea for data to be of type void *const so you can't accidentally do something like data = item->data instead of item->data = data .在这个 function 中, data并不意味着要修改,所以data类型为void *const似乎是个好主意,这样你就不会意外地执行类似data = item->data而不是item->data = data之类的事情.

The next level would be to define data as const void *const which means you also can't change what data points to.下一个级别是将data定义为const void *const这意味着您也无法更改data指向的内容。 However, this leads to a warning about discarding the const qualifier from the pointer.但是,这会导致有关从指针中丢弃const限定符的警告。 And if I understand correctly, further use of such a pointer is considered undefined behavior.如果我理解正确,进一步使用这样的指针被认为是未定义的行为。 Using a cast ( item->data = (void *)data ) seems clunky.使用演员表( item->data = (void *)data )似乎很笨重。

What's the best approach here?这里最好的方法是什么? Is const void *const unnecessarily over-protective? const void *const是否不必要地过度保护? It feels like void *const is sufficient to catch most errors.感觉void *const足以捕获大多数错误。

Since changes to function parameters aren't reflected in the calling function, there's little reason to make sure the parameters themselves are read-only.由于对 function 参数的更改不会反映在调用 function 中,因此没有理由确保参数本身是只读的。 It is useful however to ensure that what a pointer parameter points to doesn't change.然而,确保指针参数指向的内容不会改变很有用的。 So if you don't want what data points to to be changed, you would change the function signature to:因此,如果您不希望更改哪些data点,您可以将 function 签名更改为:

void enqueue(struct queue *q, const void *data)

Note that this will work only if the data member of struct queue_node has type const void * .请注意,这仅在struct queue_nodedata成员具有const void *类型时才有效。 If it doesn't, then you don't want to use const on the data parameter.如果不是,那么您不想在data参数上使用const

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM