Joe*_*Joe 3 c++ memory constructor destructor
我试图在全局范围中定义一个包含一些动态分配的数组的类.当调用类的构造函数时,程序无法访问通过参数文件读取的用户定义的参数(即模拟中的年数),因此无法将内存分配到适当的大小.我的想法是在类中的私有函数内分配内存,然后使用析构函数释放它.一些示例代码:
class Simulation{
private:
int initial_call; //a flag used to initialize memory
double *TransferTracker;
public:
Simulation();
~Simulation();
void calc();
};
Simulation simulator; //global instance of Simulation
Simulation::Simulation()
{
initial_call = 1;
}
Simulation::~Simulation()
{
//when calling the destructor, though, the address is
//0xcccccccc and the following attempt to delete produces
//the compiler error.
delete [] TransferTracker; //see error
}
void Simulation::calc()
{
for (int i = 0; i < num_its; i++)
{
if (initial_call)
{
TransferTracker = new double [5];
//The address assigned is, for example, 0x004ce3e0
initial_call = 0;
}
}
//even if this calc function is called multiple times, I see
//that the address is still 0x004ce3e0.
}
Run Code Online (Sandbox Code Playgroud)
我从上面的代码片段收到的错误是:
Unhandled exception at 0x5d4e57aa (msvcr100d.dll) in LRGV_SAMPLER.exe: 0xC0000005: Access
violation reading location 0xccccccc0.
Run Code Online (Sandbox Code Playgroud)
这个错误是有道理的,因为我在输入析构函数时检查了TransferTracker的内存地址.我的问题是,为什么我们在输入析构函数时会丢失地址?它可能与模拟器是全局的事实有关; 如果班级不是全球性的,那么这种范式似乎工作正常.我是面向对象编程的新手,所以任何帮助都表示赞赏!
编辑:这基本上是我的错误,并得到答案的帮助.发生了两个问题:(1)指针从未设置为NULL,因此在尝试删除未分配的指针时会产生混淆.(2)在我的范围内实际上有两个类的实例,这是我的错误.在最终的代码中,只会有一个实例.感谢大家!
将指针初始化为NULL(0)
Simulation::Simulation() : TransferTracker(NULL)
{
initial_call = 1;
}
Simulation::~Simulation()
{
//when calling the destructor, though, the address is
//0xcccccccc and the following attempt to delete produces
//the compiler error.
if(TransferTracker) delete [] TransferTracker; //see error
TransferTracker = NULL;
}
Run Code Online (Sandbox Code Playgroud)
这样你可以检查是否已经初始化它想要删除它.这是最好的做法,所以总是这样做,不仅仅是在施工时
编辑:
void Simulation::calc()
{
for (int i = 0; i < num_its; i++)
{
if (initial_call)
{
if(TransferTracker) delete [] TransferTracker;
TransferTracker = new double [5];
initial_call = 0;
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1287 次 |
| 最近记录: |