Search code examples
c++constantsusing

difference between `using` and plugging in directly


Consider the 2 snippets:

using x = int*;

int main () {
  const x a = new int(3);
  *a = 5;
}

and

int main () {
  const int* a = new int(3);
  *a = 5;
}

The first compiles, while the second doesn't

--> using is not equivalent to simply "plugging in" the type and then parse the line.

Are there more differences between using using and "inlining" the type directly?


Solution

  • The difference in interpretation is due to the way C++ declarations deal with pointer const-ness, which borrows its semantics from C. Basically, const int* x and int * const x mean different things, as explained in this Q&A.

    In turn, this interpretation is due to the way the "anonymous" pointer types are derived syntactically: language designers decided to assigning const-ness to the pointed-to value, not the pointer itself, when const is at the front of the declaration.

    Note that the same thing happens when you typedef a pointer type:

    typedef int* x;
    
    int main () {
        const x a = new int(3);
        *a = 5; // Works fine
        return 0;
    }
    

    Essentially, adding a using or typedef makes C++ treat int* as a single type, with only one way of assigning const-ness. On the other hand, writing int* directly is treated as a "derived" pointer type, which is governed by a different set of rules.