我应该在 C++ 做什么?对于以下 C 代码?
对于 C 中的以下代码,我应该在 C++ 中做什么?
struct Node* node = (struct Node*)malloc(sizeof(struct Node));
我应该使用“新”吗? 谢谢
what should I do in C++ for following code in C?
struct Node* node = (struct Node*)malloc(sizeof(struct Node));
Should I use "new"?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
使用new,不需要强制转换:
完成后,使用delete而不是free来释放内存:
但是,推荐使用shared_ptr:
使用shared_ptr,不需要显式删除struct实例。当节点超出范围时,它将被删除(如果它还没有被共享,否则当指向它的最后一个shared_ptr超出范围时,它将被删除)。
Use new and no cast is needed:
When finished, use delete instead of free to deallocate the memory:
However, recommend using shared_ptr:
With shared_ptr, no need to explicitly delete the struct instance. When node goes out of scope, it will be deleted (if it hasn't been shared, otherwise it will be deleted when the last shared_ptr that points to it goes out of scope).
是的,您想使用
new
:您可以在升压、C++0x 和 TR1。它将为您处理释放,确保您没有内存泄漏。如果您使用 boost,则需要包含并使用 boost::shared_ptr。
Yes, you want to use
new
:You can find shared_ptr in boost, C++0x and TR1. It will handle deallocation for you, ensuring you don't have a memory leak. If you use boost, you want to include and use boost::shared_ptr.
最好使用
new
,因为malloc
不会调用构造函数,因此如果使用malloc,
它只分配所需的内存。Node
将不会被“构造”另一方面,
new
先分配内存,然后调用构造函数,这样效果更好。编辑:
如果您使用
malloc
,您可能会遇到这样的问题:(必须看到)为什么当我尝试插入树时会出现分段错误*
Its better to use
new
becausemalloc
doesn't call the constructor, soNode
will not be "constructed" if you usemalloc
which only allocates the required memory.On the other hand,
new
first allocates the memory and then calls the constructor which is better.EDIT:
If you use
malloc
, you might run into such problems: (must see)Why do I get a segmentation fault when I am trying to insert into a tree*
在 C++ 中,您几乎应该始终使用
new
而不是malloc
,尤其是在创建非 POD 对象时。因为new
会调用类的适当构造函数,而malloc
则不会。如果新创建的对象没有调用构造函数,那么您得到的只是一个指向垃圾的指针。考虑以下示例:
You should almost always use
new
instead ofmalloc
in C++, especially when you are creating non-POD objects. Becausenew
will envoke appropriate constructor of the class whilemalloc
won't. If constructor is not called for newly-created object, what you get is a pointer pointing to a piece of junk.Consider following example:
Node *node = new Node;
这应该具有完全相同的效果。
Node *node = new Node;
That should have the exact same effect here.