繁体   English   中英

访问用malloc分配的C ++对象的成员?

[英]Accessing member of a C++ object allocated with malloc?

[编者注:我已经编辑了标题,以期在将来对其他人有用。 为了给答题者一个荣誉,这仅仅是“为什么这不起作用?” 他们回答的时候有问题!]

以下代码由于分段错误而在top -> ...行崩溃,无论将什么Node*试图插入向量子级。 有谁知道这可能是什么原因?

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);
}

问题是malloc不会调用构造函数。 您指望要构造的向量children

更换:

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

带有:

Node* temp = new Node;

malloc (来自C)和new (来自C ++)都将分配所需的内存,但只有new会调用所需的构造函数,因为C不使用它们。 如果您不确定是否需要malloc,请使用new。

您不要在对象上使用malloc ,而应该使用new malloc是一个C函数,仅分配一块内存,而C ++运算符std::new也负责对象的初始化和构造-您在此处错过的步骤,这会造成麻烦(例如temp->children的构造函数) temp->children在您的情况下从未召集temp->children )。

根据经验:如果要编写C ++代码,则应使用C ++运算符std::newstd::delete进行动态内存分配和释放,而不是C函数。

您的问题是children向量未正确初始化。 您应该使用Node* temp = new Node; 代替malloc呼吁构造Node ,它调用的构造函数children ,从而正确初始化vector

正如其他人所评论的那样,您似乎来自C语言,并且需要一本好书。 C ++不仅是“带有class es的C”!

您的push函数看起来非常像应该是构造函数 构造函数在分配了所需的内存并执行了必要的初始化之后,将被new调用。 如果您不提供编译器,则编译器将为您生成一个(它还将提供一个复制构造函数和一个赋值运算符(请参阅“三的规则是什么?” )。

由于您调用了malloc()而不是new ,因此未调用综合默认构造函数,因此未初始化children vector ,从而导致访问冲突。

在这里,我演示了如何实现默认构造函数(并禁用其他两个构造函数)以初始化class (或struct )的三个数据成员中的每个成员:

#include <string>
#include <vector>
using std::vector;
using std::string;

class Node
{
public:
    Node(const string& word, Node* top)
        :data(word)
        ,parent(top)
        ,children()
    {
        if (top != NULL)
        {
            top->children.push_back(this);
        }
    }

    virtual ~Node()
    {
        std::vector<Node*>::iterator i = std::find(children.begin(), children.end(), this);
        if (i != children.end())
        {
            parent->children.erase(i);
        }
        // TODO: You may wish to destory children at this point
    }

private:
    Node(const Node& disable);
    Node& operator =(const Node& disable);

private:
    string data;
    Node* parent;
    vector<Node*> children;
};

int main()
{
    Node top("blah", NULL);
    Node child("foo", &top);
}

我还实现了一个析构函数 ,它在销毁时从其父级的子级中删除一个节点。

malloc()仅分配一个空的内存块,您应该使用new()运算符来初始化所有成员对象;

Node* temp = new Node();

暂无
暂无

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

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