双指针在使用 new 时不调用对象构造函数

Double pointer doesn't call object constructor when using new

本文关键字:调用 对象 构造函数 new 指针      更新时间:2023-10-16

我的问题似乎只能用单个指针来回答。我正在尝试为一个2d链表进行动态分配。当我试图使用类llist构造函数将头和尾指针设置为NULL时遇到的问题:

//I've included only the parts that I see are neccesary
struct node {
int value ;
int weight ;
node* next ;
} ;
class  llist{
private :
node* tail, *head ;
public :
llist(){tail = NULL ;  head = NULL ;} /* this unneccesary retype is to make sure 
that it wasn't a typo*/
}
class list_graph
{
private :
int size, s;
llist ** v ;
public :
list_graph(int s){
this -> s = s ;
size = 0 ;
v = new llist* [s] ; 
}
}

我已经使用了调试器并运行了每一个步骤,在我创建了list_graph类型的对象后,似乎没有调用我的llist构造函数,所以其他所有依赖它的函数都会失败,并导致分段错误。我做错了什么吗,或者除了使用STL列表之外还有什么解决办法吗,非常感谢

这:

v = new llist* [s] ; 

创建指向类型llist的指针数组,但不创建任何llist对象。如果你想要一系列这样的东西,那么你想要:

llist * v ;  

和:

v = new llist[s] ; 

或者更好的是,如果这不是家庭作业,请使用std::vector。不要把llist ** v之类的东西看作是"双指针";把它们想象成它们是什么——指针对指针。

如果你想分配一个2D指针数组,你可以用两种方法:

使用指针数组的动态数组,给定一些widthheight:

llist** data = new llist*[width];
for (int i = 0; i < width; ++i){
data[i] = new llist[height]; // constructors get called here
}
// accessing a linked list, make sure x is in [0, width) and y is in [0, height):
data[x][y]->value;

使用单指针数组:

llist* data = new llist[width * height]; // constructors get called here
// accessing a linked list:
// again, make sure x is in [0, width) and y is in [0, height)
data[x + (y * width)]->value;

如果您想将v保留为指向llist对象的指针数组,而不是llist对象的数组(Neil Butterworth建议(,请通过将list_graph构造函数更改为来动态分配每个指针

list_graph(int s) : size(0), s(s), v(new llist* [s]) {
for (int i(0); i < s; ++i)
v[i] = new llist();
}

EDIT:为了避免在for循环中调用news次,可以一次预分配所有sllist对象。然而,这意味着它们不能单独删除。你的课看起来像

class list_graph {
int size, s;
llist* buffer;
llist ** v ;
public:
list_graph(int s) : size(0), s(s),
buffer(new llist[s]), v(new llist* [s]) {
for (int i(0); i < s; ++i)
v[i] = &buffer[i];
}
~list_graph() {
delete[] v;
delete[] buffer;
}
};