Search code examples
c++typedef

Is there a difference between use const keyword inside typedef and outside typedef?


I have written a typedef like the following:

typedef wchar_t *cString;

and I put the const keyword independently as follow:

void func(const cString)

But when passing wstring::c_str() to the previous method func(wstring::c_str()), it tells me there's an error argument of type "const wchar_t *" is incompatible with parameter of type "cString", although the type cString is wchar_t * with an independent const.

and to resolve that problem I must either define the typedef as typedef const wchar_t *cString; or use const wchar_t* directly without typedef.

Why that problem occurred?


Solution

  • typedef wchar_t *cString; declares cString as a mutable pointer to mutable data.

    const cString declares a const one of these, which is therefore a const pointer to mutable data. The matching typedef for this would be typedef wchar_t(*const cString);, I think. (One wouldn't normally typedef a const pointer like this, so I'm not 100% certain on the syntax)

    However, wstring::c_str() returns a mutable pointer to const data. The matching typedef for this would be typedef (const wchar_t) *cString;, with or without parenthesis.

    Therefore func(wstring::c_str()) is passing a (mutable) pointer to const data, to a function that expects a (const) pointer to mutable data. The pointer itself can be converted from mutable to const, but the data it points to can't be silently converted from const to mutable, so it tells you something is wrong.