Re: [HACKERS] Add some const decorations to prototypes

Поиск
Список
Период
Сортировка
От Tom Lane
Тема Re: [HACKERS] Add some const decorations to prototypes
Дата
Msg-id 29306.1510329297@sss.pgh.pa.us
обсуждение исходный текст
Ответ на Re: [HACKERS] Add some const decorations to prototypes  (Fabien COELHO <coelho@cri.ensmp.fr>)
Ответы Re: [HACKERS] Add some const decorations to prototypes
Список pgsql-hackers
Fabien COELHO <coelho@cri.ensmp.fr> writes:
>>> ISTM That there is still at least one strange cast:
>>>> +static const char **LWLockTrancheArray = NULL;
>>>> +               LWLockTrancheArray = (const char **) // twice

>> These are not cases of "cheating".  This is just the return value of a
>> memory allocation function being cast from void * to the appropriate
>> result type.  That is an orthogonal style decision that I have
>> maintained in these cases.

> Would it make sense that the function returns "const void *", i.e. the 
> cast is not on the const part but on the pointer type part?

Certainly not -- if malloc-like functions returned "const void *" then
you could never write on allocated space without having casted away
const.

In any case, what's shown above is not involving any funny stuff,
because the type of LWLockTrancheArray is pointer to non-const
array of pointers to const char strings.  So it's correct to be
assigning a non-const pointer to it.  If it were written like
"const char * const *" then the issues would be quite different.

As for your followup --- yes, we could just omit the cast altogether
and the compiler wouldn't complain, but that is not better style IMO.
The value of the cast really is to document what type we're expecting
the expression to produce.  In context, that statement (today) is
       LWLockTrancheArray = (char **)           MemoryContextAllocZero(TopMemoryContext,
 LWLockTranchesAllocated * sizeof(char *));
 

and the reader can see by inspection that the calculation of how much
to allocate (so many char-* items) is consistent with the char-**
result.  It is not necessary to go find the declaration of
LWLockTrancheArray and verify that it's char **, because we trust the
compiler to whine if char ** isn't assignment-compatible with that.
But if we left off the cast and just assigned the function result directly
to the variable, then there would be nothing directly tying the variable's
type to this allocation computation.
        regards, tom lane


-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers

В списке pgsql-hackers по дате отправления:

Предыдущее
От: Robert Haas
Дата:
Сообщение: Re: [HACKERS] Simplify ACL handling for large objects and removal ofsuperuser() checks
Следующее
От: Pavel Stehule
Дата:
Сообщение: Re: [HACKERS] proposal: psql command \graw