访问分配有malloc的C ++对象的成员? [英] Accessing member of a C++ object allocated with malloc?

查看:134
本文介绍了访问分配有malloc的C ++对象的成员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



以下代码在 top - > ... 与分段错误,不管 Node * 试图被推送到向量子节点。是否有人知道是什么原因导致的?

  struct Node 
{
string data;
struct Node * parent;
vector< struct Node *>儿童;
};

struct Node * push(string word,struct Node * top)
{
Node * temp =(struct Node *)malloc
temp - > data = word;
temp - > parent = top;
return temp;
}

int main()
{
Node * top = push(blah,NULL);
Node * temp = NULL;
top - > children.push_back(temp);
}


解决方案

问题是 malloc 不会调用构造函数。

替换:

$ b $

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

有:

 code> Node * temp = new Node; 

malloc new (从C ++)都将分配所需的内存,但只有 new 会调用所需的构造函数,如C不使用它们。如果你不肯定你需要malloc,使用新的。


[Editor's note: I have edited the title to try to make this useful to others in the future. To give the answerers credit, this was just a "why does this not work?" question when they answered it!]

The following code crashes at the top -> ... line with a segmentation fault, regardless of what Node* is trying to be pushed onto the vector children. Does anyone know what might be causing this?

struct Node
{
    string data;
    struct Node* parent;
    vector<struct Node*> children;
};

struct Node* push(string word, struct Node* top)
{
    Node* temp = (struct Node*) malloc(sizeof(struct Node));
    temp -> data = word;
    temp -> parent = top;
    return temp;
}

int main()
{
    Node* top = push("blah", NULL);
    Node* temp = NULL;
    top -> children.push_back(temp);
}

解决方案

The problem is that malloc will not call constructors. And you're counting on the vector children to be constructed.

Replace:

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

With:

Node* temp = new Node;

malloc (from C) and new (from C++) will both allocate the memory you need, but only new will call the required constructors, as C doesn't use them. If you're not positive that you need malloc, use new.

这篇关于访问分配有malloc的C ++对象的成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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