开发者

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

what should I do in C++ for following co开发者_运维技巧de 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).


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.


Its better to use new because malloc doesn't call the constructor, so Node will not be "constructed" if you use mallocwhich 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*


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜