【发布时间】:2011-05-31 19:14:56
【问题描述】:
原来这是一个简单的构造函数误用问题。 有关更新信息,请参阅“编辑”部分。
抱歉,还有一个 C++ dtor 问题... 但是我似乎找不到一个与我的完全一样的,因为所有其他容器都分配给 STL 容器(这将删除对象本身),而我的是一个指针数组。
所以我有以下代码片段
#include<iostream>
class Block{
public:
int x, y, z;
int type;
Block(){
x=1;
y=2;
z=3;
type=-1;
}
};
template <class T> class Octree{
T* children[8];
public:
~Octree(){
for( int i=0; i<8; i++){
std::cout << "del:" << i << std::endl;
delete children[i];
}
}
Octree(){
for( int i=0; i<8; i++ )
children[i] = new T;
}
// place newchild in array at [i]
void set_child(int i, T* newchild){
children[i] = newchild;
}
// return child at [i]
T* get_child(int i){
return children[i];
}
// place newchild at [i] and return the old [i]
T* swap_child(int i, T* newchild){
T* p = children[i];
children[i] = newchild;
return p;
}
};
int main(){
Octree< Octree<Block> > here;
std::cout << "nothing seems to have broken" << std::endl;
}
查看输出,我注意到析构函数在我认为应该调用之前被调用了很多次(因为 Octree 仍在范围内),输出的结尾还显示:
del:0
del:0
del:1
del:2
del:3
Process returned -1073741819 (0xC0000005) execution time : 1.685 s
Press any key to continue.
由于某种原因,析构函数在循环中经过同一点两次 (0),然后死亡。
所有这一切都发生在“似乎没有任何问题”行之前,这是我在调用任何 dtor 之前所期望的。
提前致谢:)
编辑 我发布的代码删除了一些我认为不必要的东西,但是在复制和编译我粘贴的代码后,我不再收到错误。 我删除的是代码的其他整数属性。 以下是原文:
#include<iostream>
class Block{
public:
int x, y, z;
int type;
Block(){
x=1;
y=2;
z=3;
type=-1;
}
Block(int xx, int yy, int zz, int ty){
x=xx;
y=yy;
z=zz;
type=ty;
}
Block(int xx, int yy, int zz){
x=xx;
y=yy;
z=zz;
type=0;
}
};
template <class T> class Octree{
int x, y, z;
int size;
T* children[8];
public:
~Octree(){
for( int i=0; i<8; i++){
std::cout << "del:" << i << std::endl;
delete children[i];
}
}
Octree(int xx, int yy, int zz, int size){
x=xx;
y=yy;
z=zz;
size=size;
for( int i=0; i<8; i++ )
children[i] = new T;
}
Octree(){
Octree(0, 0, 0, 10);
}
// place newchild in array at [i]
void set_child(int i, T* newchild){
children[i] = newchild;
}
// return child at [i]
T* get_child(int i){
return children[i];
}
// place newchild at [i] and return the old [i]
T* swap_child(int i, T* newchild){
T* p = children[i];
children[i] = newchild;
return p;
}
};
int main(){
Octree< Octree<Block> > here;
std::cout << "nothing seems to have broken" << std::endl;
}
此外,对于 set_child、get_child 和 swap_child 可能导致内存泄漏的问题,这将得到解决,因为包装类将在 set 之前使用 get 或使用 swap 来获取旧子节点并在释放之前将其写入磁盘记忆本身。
我很高兴这不是我的内存管理失败,而是另一个错误。 我还没有制作副本和/或赋值运算符,因为我只是在测试块树,我几乎肯定会很快将它们全部设为私有。
这个版本吐出-1073741819。
感谢大家的建议,对于劫持我自己的帖子我深表歉意:$
已解决 一个构造函数调用另一个构造函数的问题。
感谢大家的帮助,对浪费的时间表示歉意:)
【问题讨论】:
-
除其他外,您还有一些严重的内存泄漏;例如:
children[i] = newchild;。您是否考虑过使用拥有资源的智能指针,例如auto_ptr或shared_ptr? -
很容易计算,在销毁
Octree< Octree<Block> > here;del= ...时会打印64次。现在,问题是什么? -
为我工作。实际问题是什么?注意(我预计 del 会被打印 72 次,我得到 72 (8*8 + 8) 快速浏览显示它们似乎是正确的顺序)。
-
抱歉,我删除了 Block 和 Octree 的一些其他整数属性,错误似乎源于它们,我的完整代码现在在我的原始帖子中的“编辑”之后,对此非常抱歉。
标签: c++ memory dynamic destructor