简体   繁体   English

对于 C 中的以下代码,我应该在 C++ 中做什么?

[英]what should I do in C++ for following code in C?

what should I do in C++ for following code in C?对于 C 中的以下代码,我应该在 C++ 中做什么?

struct Node* node = (struct Node*)malloc(sizeof(struct Node));

Should I use "new"?我应该使用“新”吗? Thanks谢谢

Use new and no cast is needed:使用 new 并且不需要强制转换:

Node* node = new Node;

When finished, use delete instead of free to deallocate the memory:完成后,使用 delete 而不是 free 释放 memory:

delete node;

However, recommend using shared_ptr:但是,建议使用 shared_ptr:

#include <memory>

std::shared_ptr<Node> node(new Node);

With shared_ptr, no need to explicitly delete the struct instance.使用 shared_ptr,无需显式删除结构实例。 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).当节点离开scope时,会被删除(如果没有被共享,否则会在指向它的最后一个shared_ptr超出范围时被删除)。

Its better to use new because malloc doesn't call the constructor, so Node will not be "constructed" if you use malloc which only allocates the required memory.最好使用new ,因为malloc不调用构造函数,因此如果使用malloc仅分配所需的 memory,则不会“构造” Node

On the other hand, new first allocates the memory and then calls the constructor which is better.另一方面, new先分配 memory 然后调用构造函数,这样更好。

EDIT:编辑:

If you use malloc , you might run into such problems: (must see)如果你使用malloc ,你可能会遇到这样的问题:(必看)

Why do I get a segmentation fault when I am trying to insert into a tree* 当我尝试插入树时为什么会出现分段错误*

Yes, you want to use new :是的,您想使用new

shared_ptr<Node> node(new Node);

You can find shared_ptr in boost , C++0x and TR1.你可以在boost 、C++0x 和 TR1 中找到 shared_ptr。 It will handle deallocation for you, ensuring you don't have a memory leak.它将为您处理解除分配,确保您没有 memory 泄漏。 If you use boost, you want to include and use boost::shared_ptr.如果你使用 boost,你想包含并使用 boost::shared_ptr。

You should almost always use new instead of malloc in C++, especially when you are creating non-POD objects.您应该几乎总是在 C++ 中使用new而不是malloc ,尤其是在创建非 POD 对象时。 Because new will envoke appropriate constructor of the class while malloc won't.因为new将调用 class 的适当构造函数,而malloc不会。 If constructor is not called for newly-created object, what you get is a pointer pointing to a piece of junk.如果新创建的 object 没有调用构造函数,你得到的是一个指向一个垃圾的指针。

Consider following example:考虑以下示例:

class MyClass
{
public:
    vector<int> m_array;
    void insert();
};
void check::insert()
{
    MyClass *root = (MyClass*)malloc(sizeof(MyClass));

                    -- This will crash your program because internal vector object
                  v -- has not been initialized yet
    root->m_array.push_back(0);
}

Node *node = new Node;

That should have the exact same effect here.在这里应该有完全相同的效果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM