双指针在使用 new 时不调用对象构造函数
Double pointer doesn't call object constructor when using new
我的问题似乎只能用单个指针来回答。我正在尝试为一个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指针数组,你可以用两种方法:
使用指针数组的动态数组,给定一些width
和height
:
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循环中调用new
s
次,可以一次预分配所有s
llist
对象。然而,这意味着它们不能单独删除。你的课看起来像
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;
}
};
相关文章:
- 是什么让放置新调用对象的构造函数?
- 当我调用对象的方法时,对象的成员会发生变化
- 为什么静态数组成员变量在调用对象的实例后不显示任何内容?
- 这个C++编译器优化(在自身的实例上调用对象自己的构造函数)的名称是什么,它是如何工作的?
- 如何从构造函数副本 T(const T&)调用对象 T?
- C++17 如何保存泛型可调用对象以供以后使用
- 检查模板中 nullptr 的函数指针,了解任何类型的可调用对象
- 是否可以在编译时初始化对象的 C 样式函数指针,以便它调用对象的成员函数?
- 如何在C++中将可调用对象放入地图中?
- 在销毁期间从另一个线程调用对象上调用方法是否未定义行为?
- 广义 std::function (std::any 表示可调用对象)
- c++ 替换调用对象方法的宏函数
- 将可调用对象传递给采用 std::function 的构造函数
- 双指针在使用 new 时不调用对象构造函数
- 可调用对象作为默认模板参数
- 只需调用对象即可获取对象数据
- 如果用户尝试从 JS 调用对象的未定义函数C++则回调C++代码
- 如何将当前替代类型的 std::variant 传递给可调用对象?
- C++对象本身作为参数调用对象的方法
- 从移交的类调用对象