cjh*_*cjh 2 c++ memory destructor dynamic
原来这是一个简单的构造函数错误使用问题. 有关更新的信息,请参阅"编辑"部分.
很抱歉还有另一个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;
}
Run Code Online (Sandbox Code Playgroud)
通过输出我注意到析构函数在我认为应该被调用之前已经被多次调用(因为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.
Run Code Online (Sandbox Code Playgroud)
由于某种原因,析构函数在循环中经过两次(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;
}
Run Code Online (Sandbox Code Playgroud)
另外,至于set_child,get_child和swap_child导致可能的内存泄漏的问题,这将解决,因为包装类将在设置之前使用get或使用swap来获取旧子并在释放内存之前将其写入磁盘.
我很高兴我的内存管理不是失败而是另一个错误.我还没有制作副本和/或赋值操作符,因为我只是测试块树,我几乎肯定会很快将它们全部私有化.
此版本吐出-1073741819.
谢谢大家的建议,我为劫持我自己的线程而道歉:$
解决 了一个构造函数调用另一个的问题.
感谢所有人的帮助和道歉,浪费时间:)
| 归档时间: |
|
| 查看次数: |
2751 次 |
| 最近记录: |