我需要创建稍后由线程处理的类队列。问题是每次我添加对对象的引用时,队列都会为该类分配内存,从而导致巨大的内存泄漏。这也导致程序在退出时挂起。
将 12345678 对 TaskClass 对象的引用添加到 TaskQueue 会导致 137MB 内存泄漏。请注意,调用 queue.pop() 时不会释放内存。
类任务队列:
template <class tjob>
class TaskQueue
{
private:
std::queue<tjob> _taskqueue;
public:
TaskQueue()
{
//constructor goes here
}
//add task to queue
template < typename Class>
bool AddTask( Class &PClass)
{
_taskqueue.push(PClass);
return true;
}
bool ProcessQueue()
{
while (!_taskqueue.empty())
{
_taskqueue.front().run();
_taskqueue.pop();
}
return true;
}
//run a function pointer
template < typename Task >
bool RunTask( Task task){
task();
return true;
}
//call class entry point member .run
template < typename Class>
bool RunClass ( Class& PClass){
PClass.run();
return true;
}
//return remaining tasks
int GetRemainingTasks(){
return _taskqueue.size();
}
};
类任务类:
class TaskClass
{
protected:
int *ptr_x;
public:
TaskClass() {
std::cout << "TaskClass Constructor called\n";
ptr_x = new int(0);
}
bool run(){
*ptr_x = *ptr_x + 1;
return true;
}
bool printx(){
std::cout << "x is now " << *ptr_x << std::endl;
return true;
}
~TaskClass(){
//std::cout << "TaskClass destructor called!\n";
}
};
主要的:
int main()
{
TaskClass job1;
int nojobs = 12345678;
TaskQueue<TaskClass> TestQueue;
std::cout << "Preparing Queue... Adding " << nojobs << " tasks.. "; //std::cin.get();
for (int i=0;i<nojobs;i++)
TestQueue.AddTask(job1);
std::cout << "Done!\n"; //std::cin.get();
std::cout << "Processing Queue... ";
TestQueue.ProcessQueue();
std::cout << "Done!\n";
job1.printx();
std::cout << "Remaining tasks: " << TestQueue.GetRemainingTasks() << std::endl;
//std::cin.get();
//exit(0);
return 0;
}