[英]Can I really initialize an array with round brackets?
Occasionaly, I've made a typo in one place of code of my program: 偶尔,我在我的程序代码的一个地方写了一个拼写错误:
int a = 10;
char* b = new char(a);
Error is obvious: I've written () instead of []. 错误是显而易见的:我写了()而不是[]。 The strange thing is... code compiled ok, it ran in debugger ok. 奇怪的是...代码编译好了,它在调试器中运行确定。 But compiled .exe outside of debugger crashed a moment after function with these lines was executed. 但是在执行这些行的函数之后,在调试器之外编译的.exe崩溃了一会儿。
Is second line of code really legitimate? 第二行代码真的合法吗? And if it is, what does it mean to compiler? 如果是,那对编译器意味着什么?
It's a single char with the numerical value of a
, in this case 10
. 这是一个单个字符与的数值a
,在这种情况下10
。 Pointers don't only point to arrays, y'know. 你知道,指针不只指向数组。
You're allocating a single char
and assigning it a value from a
. 你分配一个单一的 char
并赋予它从一个值a
。 It's not allocating an array at all. 它根本没有分配数组。
It's the same as calling the constructor in a new
expression for any other type: 它与在任何其他类型的new
表达式中调用构造函数相同:
std::string* s = new std::string("foo");
int* i = new int(10);
std::vector<std::string>* v = new std::vector<std::string>(5, "foo");
char t(a)
creates a local char initialized to the value of a
. char t(a)
创建一个初始化为a
值的本地char。
new char (a)
creates a dynamically allocated char initialized to the value of a
. new char (a)
产生初始化的值的动态分配的炭a
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.