如果我创建一个节点如下
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
。不要在 new
和 malloc
之间跳转。
其次,这不是有效的 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/