C ++语句说了什么 [英] c++ statement what it says

查看:52
本文介绍了C ++语句说了什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

帮助我解释这个问题

new1 = new node [sizeof(node)];

help me in explaining this one

new1=new node[sizeof(node)];

推荐答案

在这里,如果new1的类型是node *,那么您的语句将创建大小为node的对象数组
Here, if the type of new1 is node* then your statement will create the array of node object of size of node structure.


new 会将请求的内存分配给指针变量/对象.
new will allocate requested memory to a pointer variable/object.
int* n=new int[5]; 

将为指针n分配5个整数字节的内存(考虑到int在系统中为4个字节,将分配5 * 4 = 20个字节).
sizeof 将返回给定数据类型的内存大小.

will allocate 5 integer bytes of memory to pointer n (5 * 4 = 20 bytes will be allocated, considering int size is 4 bytes in the system).
sizeof will return memory size of the given data type.

int s=sizeof(int); 

执行此行时,s的值为4(考虑到int在系统中的大小为4个字节).

在您的代码上,节点"应该是结构或类. "new1"是类型"node"的指针.您正在分配1个对象内存并为节点"创建对象.分配的内存地址将存储在"new1"指针中. 但是,如果sizeof(node)返回20,则会将20 * sizeof(node)字节分配给new1对象.

On executing this line, s will have value 4, considering int size is 4 bytes in the system).

On your code, "node" should be a structure or a class. "new1" is the pointer of type "node". You are allocating 1 object memory and creating object for "node". Allocated memory address will be stored in "new1" pointer. But, if sizeof(node) returns 20, 20 * sizeof(node) bytes will be allocated to new1 object.

new1=new node[sizeof(node)]; 



请注意,您需要最后调用



Note that you need to call

delete[] new1;

,以释放您为new1消耗的内存.

at end to deallocate the memory you consumed for new1.


好,我会尝试解释.

首先,这似乎是由不太了解newdelete概念的人编写的,而是习惯于mallocfree的.

其次,显然new1是或应该是node*类型的变量.如果不是,那么整行可能都没有达到作者的预期.

第三,该表达式为and initializes分配一个类型为node的(sizeof(node))元素数组.通过调用每个元素的构造函数node::node()进行初始化.如果您问我,sizeof(node)部分是以前的malloc命令的剩余部分,实际上是一个错误,如上所述.
Ok, I will try to explain.

First, this seems to be coded by someone who does not really understand the concepts of new and delete, and is rather used to malloc and free.

Second, apparently, new1 is, or should be a variable of type node*. If it is not, then probably the whole line doesn''t do what the author intended.

Third, the expression allocates and initializes an array of (sizeof(node)) elements of type node. The initialization happens by calling the constructor node::node() of every element. If you ask me, the sizeof(node) part is a remnant of a former malloc command, and, in fact a mistake, as indicated above.


这篇关于C ++语句说了什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆