-2

Does the "auto" keyword in C++ have anything to do with storage class For example:

void foo() {
  auto ptr = new int[9]
}

Does the pointer to int above have is automatic(stack), or dynamic(heap)?

vic
  • 45
  • 2
  • 9
  • 1
    `auto` is not used in C++11 as a storage-class specifier. – JFMR Feb 15 '18 at 13:15
  • [What is the point of the 'auto' keyword?](https://stackoverflow.com/questions/17689733/what-is-the-point-of-the-auto-keyword) – t.niese Feb 15 '18 at 13:21
  • The above code is equivalent to `int *ptr = new int[9];`, But modern C++ doesn't like using (or abusing) `new` and `delete`, you should rethink your app in terms of `vector`, `array`, `shared_ptr`, `unique_ptr`, `weak_ptr`. – user9335240 Feb 15 '18 at 13:25

1 Answers1

3

Until c++11, auto was used to specify automaticstorage duration. But since c++11 its only meaning is that the type of the variable is automatically deduced. It has nothing to do wiith the storage-class of the variable itself.

In your case ptr is a local variable (int * ptr) pointing to a location on the heap. You can always get the same effect by explicitely writing the types of the variables as in the following:

void foo() {
  int* ptr = new int[9];
}

Please take a look at this link for more details and on how the deduction process works.

http://en.cppreference.com/w/cpp/language/auto

Davide Spataro
  • 7,319
  • 1
  • 24
  • 36