简体   繁体   中英

what should I do in C++ for following code in C?

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

Use new and no cast is needed:

Node* node = new Node;

When finished, use delete instead of free to deallocate the memory:

delete node;

However, recommend using shared_ptr:

#include <memory>

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

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).

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.

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*

Yes, you want to use new :

shared_ptr<Node> node(new Node);

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.

You should almost always use new instead of malloc in C++, especially when you are creating non-POD objects. Because new will envoke appropriate constructor of the class while malloc 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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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