c++ - 节点指针内部的指针

标签 c++ pointers data-structures malloc nodes

如果我创建一个节点如下

struct node
{
    char *ptr = (char *)malloc(sizeof(char));
}*current;
void main()
{
    node *temp = new node();
    current = temp;
}

上面的代码会自动设置current->ptr指向temp->ptr指向的地方吗?

最佳答案

struct node
{
    char *ptr = (char *)malloc(sizeof(char)); // INVALID
} *current;

首先,你不应该混用内存模型。如果您正在使用 new,请坚持使用 new。不要在 newmalloc 之间跳转。

其次,这不是有效的 C++。你不能在声明中声明一个类成员并调用一个函数来初始化它(除非你使用的是 C++11 的新特性)。更新它以清理它看起来像:

struct node
{
    char* ptr; // declare the pointer
    node() : ptr(new char) { } // initialize the pointer in the constructor
    // NOTE:  should also add a copy constructor and copy-assignment operator here
    ~node()
    {
        delete ptr; // free the memory in the destructor
    }
};

int main() // NOTE that main must return an int, not void
{
    node current = new node();
    node temp = *current; // will do a shallow copy
    // ...
    delete current;
    // PROBLEM - temp now has a dangling pointer!
    return 0;
}

另请注意,在这种情况下,ptr 没有理由必须是指针。由于您只是动态分配单个 char,因此您可以使用自动:

struct node
{
    char data;
    node() : data('\0') { }
};

int main()
{
    node current;
    node temp = current; // temp now has a copy of data, no problems
    return 0;
}

will the above code automatically set current->ptr to point where temp->ptr is pointing

您拥有的代码甚至无法编译,但如果您进行了修复,默认的复制赋值运算符将进行浅拷贝。在指针的情况下,这意味着您有 2 个对象都指向相同的内存位置。由于他们都认为自己拥有它,所以当其中一个销毁它时,另一个会留下一个悬空指针。

关于c++ - 节点指针内部的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21864059/

相关文章:

c++ - 二维数组重新分配

c++ - 使用 C++ 嵌入\扩展 Python 时的复杂数据结构

c - C语言给字符串加一个整数,如何理解结果?

c - glibc 检测到 *** free() : invalid pointer

java - Java 中使用自定义对象的属性(字段)快速搜索自定义对象的数据结构

c++ - 更新排序数据结构中的单个值

C++ 获取进程所有者/当前用户 token

c++ - 检查多态性中的真实变量类型 (C++)

c++ - 在netbeans IDE中隐藏工具栏上的进程进度条?

c++ - 我只是在查看模板并在我的书中找到了这段代码,这显示了段错误?