[Swan-dev] alloc_thingies and __typeof__

Andrew Cagney andrew.cagney at gmail.com
Fri Feb 12 15:39:16 UTC 2016


I've added type casts to:

alloc_thing(TYPE, NAME)
clone_thing(VARIABLE, NAME)
alloc_things(TYPE, COUNT, NAME) (new)

and in the process flushed out two bugs:

- an object of the wrong type was being allocated (fortunately a larger object)
- a pointer, instead of pointer target, was being cloned (fortunately
NULL resulting in an empty string)

however, for clone_thing() I used the extension __typeof__().  I've
added these notes as a rationale:

/*
 * Notes on __typeof__().
 *
 * The macro clone_thing(), for instance, uses __typeof__(THING) to
 * ensure that the type of the original THING and the returned clone
 * match.  Enforcing this flushed out a weird bug bug in the config
 * parser.
 *
 * While __typeof__() is a non-standard extension, it is widely
 * supported - GCC, LLVM, and even PCC include the feature.  MSVC
 * provides the alternative decltype(), and when someone tries to use
 * that compiler adding suitable #ifdefs should be straight forward.
 *
 * There is, however, one limitation.  If THING has the const
 * qualifier then the clone can't be assigned to a non-const variable.
 * For instance, this code gets a warning:
 *
 *    const char *p = ...;
 *    char *q = clone_thing(*p, "copy of p");
 *
 * One way round it would be to use another GCC extension ({}) and
 * change the macro to:
 *
 *    #define clone_thing(TYPE,THING,NAME) ({
 *            const (TYPE) *p = &(THING);
 *            (TYPE*) clone_bytes(p, sizeof(TYPE), (NAME);
 *       )}
 *
 * Another would be to use, er, C++'s remove_const<>.
 */

seem reasonable?

Andrew


More information about the Swan-dev mailing list