Why does C++ allow variable length arrays that aren't dynamically allocated?

我们两清 提交于 2019-11-27 05:35:54

Support for variable length arrays (VLAs) was added to the C language in C99.

It's likely that since support for them exists in gcc (to support C99), it was relatively straightforward to add support for them to g++.

That said, it's an implementation-specific language extension, and it's not a good idea to use implementation-specific extensions if you want your code to be portable.

Because it's supported in C99. I can't really speak to why it's not in the C++ standard. However, it's not as useful as you might think because it easily leads (if you're not careful) to stack overflow (since it's typically based on alloca, itself non-standard). Another mistake is to return a pointer to a dynamic array, which will immediately go out of scope.

Lot's of compilers embrace and extend standards. There are two basic reasons:

  1. Nefarious compiler-writers probably think that making it harder to move away from their compiler helps increase longevity.
  2. Benevolent compiler-writers probably think that giving you more options when they can at little to no cost to themselves is a good thing.

All of the reasons mentiond having to do with them being in C are correct, though there are limitations for the requirement. You're example may demonstrate more flexible support than what is required in C (if you implemented that using scanf rather than cin, put it in a .c file, and used gcc).

This is almost just a implicit call to alloca (allocate auto) which just decreases the stack pointer (increasing the stack size) and copies the new stack pointer to another register which is used as a pointer to the allocated memory.

The difference is that constructors and destructors aren't going to be called on objects created with a alloca.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!