0

I know that when you allocate an array with

int* arr = new int[n];

the compile creates an overhead to know how many there elements to deallocate. But does it creates an overhead to static arrays

int arr[4];

I think that the answer is no because you cannot delete[] such array, but I need to know for sure. Thanks!

3
  • Welcome to StackOverflow! Can you clarify what you mean by an overhead? Likewise, do you mean "static" in the non-dynamic sense, or "static" as in static linkage or static storage sense? Commented Apr 13, 2020 at 19:55
  • I'm not really sure that I translated this correctly from Russian language, we call arrays in the second example static and in the first example dynamic. I mean static in the sense that this is only possible to create this array with const variable or with numeric literal (thus, their size is determined during compilation) Commented Apr 13, 2020 at 20:02
  • When the "static" keyword is not used like in your example, both cases will require some CPU cycles to initialize an array of specified size, every time you create an instance of your class at runtime. The first will cost slightly more, because a constructor is involved (new) Commented Apr 13, 2020 at 20:36

1 Answer 1

2

You are right. No additional storage is required. The deallocation happens automatically in case of variables with automatic storage duration. The compiler has all the information it needs at compile-time to know when and how much memory to deallocate

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! Do you think then that creating 4 variables and array[4] can be considered the same in terms of taken memory?
Yes, it's the same. There may be some corner cases that I'm unaware of though

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.