有什么方法可以在 C++ 中声明另一个变量大小的变量吗?
Is there any way of declaring a variable of another variable's size in C++?
我真的需要在我的代码中做这样的事情:
字符 str[var+1];
但我知道你只能在 [] 之间放一个常量。所以我只是问是否有任何方法可以做我需要的事情。
只能在 C++ 中声明编译时常量大小的变量。
但是,动态数组可以具有动态大小。创建动态数组的最简单方法是使用 std::vector
,或者如果是字符串,您可以使用 std::string
。示例:
std::string str(var+1, '[=10=]');
问题最初包含 C 和 C++ 标记,此答案适用于 C
在 C 中,var
对于 VLA 支持标准(c99 和 c11 中的可选支持)可以是非常数
以下在 C 中有效(参见:https://godbolt.org/z/kUockA)
int var=3;
char str[var+1];
然而,VLA 未在 C++ 标准中定义(参见:),也不建议在 C 中使用。
因为 VLA 通常分配在堆栈上,如果 var
的值不受控制,str
的分配可能会失败,并且这种失败的恢复可能很困难。此外,他们可以鼓励创建高度不安全的代码(如果有人想在堆栈分配的变量上进行指针运算)。
有一项倡议使 linux 内核代码无 VLA(参见:https://www.phoronix.com/scan.php?page=news_item&px=Linux-Kills-The-VLA):
Using variable-length arrays can add some minor run-time overhead to the code due to needing to determine the size of the array at run-time.
VLAs within structures is not supported by the LLVM Clang compiler and thus an issue for those wanting to build the kernel outside of GCC, Clang only supports the C99-style VLAs.
Arguably most importantly is there can be security implications from VLAs around the kernel's stack usage.
我真的需要在我的代码中做这样的事情: 字符 str[var+1]; 但我知道你只能在 [] 之间放一个常量。所以我只是问是否有任何方法可以做我需要的事情。
只能在 C++ 中声明编译时常量大小的变量。
但是,动态数组可以具有动态大小。创建动态数组的最简单方法是使用 std::vector
,或者如果是字符串,您可以使用 std::string
。示例:
std::string str(var+1, '[=10=]');
问题最初包含 C 和 C++ 标记,此答案适用于 C
在 C 中,var
对于 VLA 支持标准(c99 和 c11 中的可选支持)可以是非常数
以下在 C 中有效(参见:https://godbolt.org/z/kUockA)
int var=3;
char str[var+1];
然而,VLA 未在 C++ 标准中定义(参见:),也不建议在 C 中使用。
因为 VLA 通常分配在堆栈上,如果 var
的值不受控制,str
的分配可能会失败,并且这种失败的恢复可能很困难。此外,他们可以鼓励创建高度不安全的代码(如果有人想在堆栈分配的变量上进行指针运算)。
有一项倡议使 linux 内核代码无 VLA(参见:https://www.phoronix.com/scan.php?page=news_item&px=Linux-Kills-The-VLA):
Using variable-length arrays can add some minor run-time overhead to the code due to needing to determine the size of the array at run-time.
VLAs within structures is not supported by the LLVM Clang compiler and thus an issue for those wanting to build the kernel outside of GCC, Clang only supports the C99-style VLAs.
Arguably most importantly is there can be security implications from VLAs around the kernel's stack usage.