c++c++20variable-types

Are there cases in C++ where the auto keyword can't be replaced by an explicit type?


I came across the following code:

auto x = new int[10][10];

Which compiles and runs correctly but I can't figure out what would be the type for defining x separately from the assignment.

When debugging the type shown is int(*)[10] for x but int (*) x[10]; (or any other combination I tried) is illegal.

So are there cases where auto can't be replaced by an explicit type...? (and is this such a case?)


Solution

  • The type of x is int (*)[10]. There are different ways of figuring this out. The simplest is to just try assigning 5 to x and noticing what the error says:

    error: invalid conversion from 'int' to 'int (*)[10]' [-fpermissive]
       13 |     x = 4;
          |         ^
          |         |
          |         int
    

    Or just use static_assert:

    static_assert(std::is_same<decltype(x), int(*)[10]>::value);
    

    This means that if you want to explicitly create x(without using auto) then you can do it as:

    int (*x)[10] = new int[10][10];
    

    Are there cases in C++ where the auto keyword can't be replaced by an explicit type?

    Now coming to the title, one example where auto cannot be directly replaced by explicitly writing a type is when dealing with unscoped unnamed enum as shown below: Demo

    enum
    {
        a,b,c
    }obj;
    
    int main()
    {
    //--vvvv----------->must use auto or decltype(obj)
        auto  obj2 = obj;
    }
    

    Similarly, when dealing with unnamed class. Demo.