What is the right way to typedef a type and the same type's pointer?

后端 未结 6 1218
我寻月下人不归
我寻月下人不归 2020-12-07 03:30

What is the right way to typedef a type and the same type\'s pointer? Here is what I mean. Should I do this:

typedef unsigned int delay;
typedef unsigned int         


        
6条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-07 03:58

    typedefing raw pointer types is pointless (ha!). It doesn't provide any real abstraction (consumers must still understand that the types are pointers, and they must figure out how to parse whatever naming convention you use for the typename to determine what the pointee type is).

    It's also bad form because if you have:

    typedef T* T_ptr;
    

    Then const T* foo and const T_ptr bar are two very different things. (foo is a pointer to a const T; it's a promise not to mutate the pointee through that pointer. bar is a pointer that is itself const; it can't be changed to point to something else.)

    The first case (pointer-to-const) is important: it helps to enforce function contracts.

    The second case is much, much less useful.

    Therefore if you were to add a typedef for a pointer type, to be useful you'd need to create two:

    typedef T* T_ptr;
    typedef const T* const_T_ptr;
    

    A tolerable exception is in C++ when you have smart pointer classes. In these cases, typing boost::shared_ptr might be tedious enough that creating a typedef for it is a reasonable convenience.

提交回复
热议问题