使用std :: vector< somepointer *>管理内存 [英] Managing memory with std::vector<somepointer*>

查看:96
本文介绍了使用std :: vector< somepointer *>管理内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





我写了以下库存管理系统,我遇到了潜在的内存泄漏,我不确定如何处理。这里有两个问题;



1. std :: vector< Item *>项目存储指向需要删除的项目的指针,以便在游戏结束时释放内存 - 因为它是一个成员变量,当删除PlayerInventory时项目本身将被删除,但是对于它包含的指针,我不知道如何管理它们。



2.在RemoveItemsOfType中,我创建一个名为nullItem的新项,并将给定位置的项设置为nullItem。我之前是否需要调用'删除项目[slot];'才能释放当前项目所占用的内存,然后用nullItem替换它?



 #includeItem.h

void Item :: Init(ItemType type)
{
this-> type = type;
}

ItemType Item :: GetType()
{
返回类型;
}

 #includePlayerInventory.h

PlayerInventory :: PlayerInventory()
{
for( int i = 0; i< slots; i ++)
{
Item * item = new Item();
item-> Init(ItemType :: NONE);
items.push_back(item);
}
}

void PlayerInventory :: SetItem(int slot,Item * item)
{
items [slot] = item;
}

Item * PlayerInventory :: GetItem(int slot)
{
return items [slot];
}

void PlayerInventory :: RemoveItemsOfType(ItemType type)
{
for(int i = 0; i< slots; ++ i)
{
if(GetItem(i) - > GetType()== type)
{
Item * nullItem = new Item();
nullItem-> Init(ItemType :: NONE);
SetItem(i,nullItem);
}
}
}





我尝试了什么:



非常想要做什么,但不知道答案,所以来这里咨询:)

解决方案

< blockquote>使用智能指针。试试,例如

  #include   <   iostream  >  
#include < vector >
#include < memory > ;
使用 命名空间标准;

class F
{
int f;
public
F( int f):f(f){cout< ;< F(<< f<< )ctor称为\ n;}
~F(){cout<< F(<< f<< )dtor名为\ n;}
};

int main()
{
vector< F *> v;
v.push_back( new F( 1 ));

vector<的unique_ptr< F> >瓦;
w.push_back(make_unique< F>( 2 ));
}



输出:

 F(1)ctor叫
F(2) ctor叫
F(2)dtor叫


经验法则是,创建内存的人必须删除它。因此,当你删除一个向量时,你必须删除内存。



但你有另外一个问题,你的向量可能被复制或分配到向量实现的深处所以你可能有2个具有相同内存的向量。也许有助于覆盖这些运算符,在这些运算符中你复制了sourse向量的内存。



我认为你不需要用new分配Item,但可以使用键入的矢量

 std: :矢量<项目> myList; 


我发现是的,你必须手动删除指针向量。如果您使用Visual Studio和DEBUG_NEW宏,则会在调试器中看到内存泄漏。至少,我这样做。我刚才想出了这个小模板函数来帮助解决这种情况:

  //  删除使用新 

模板创建的对象矢量< typename T>
void DeleteVector(std :: vector< T>& v)
{
size_t count = v.size();
for size_t n = 0 ; n< count; ++ n)
delete (v [n]);
v.clear(); // 只是为了确保
}

如果你使用的话malloc变量分配指针然后你可以使这个函数的变体调用free而不是delete,因为free不是类型化的操作,函数不需要是模板。


Hi,

I've written the following inventory management system, and I've come across a potential memory leak which I'm unsure how to handle. There are two issues here;

1. The std::vector<Item*> items is storing pointers to items which need to be deleted to free memory when the game ends - as it's a member variable, items itself will be deleted when PlayerInventory is deleted, but as for the pointers it contains, I'm not sure how to manage them.

2. In RemoveItemsOfType, I create a new item called nullItem and set the item in the given position to nullItem. Do I need to call 'delete items[slot];' before I do this to free the memory held by the item currently there, before I replace it with nullItem?

#include "Item.h"

void Item::Init(ItemType type)
{
	this->type = type;
}

ItemType Item::GetType()
{
	return type;
}

#include "PlayerInventory.h"

PlayerInventory::PlayerInventory()
{
	for (int i = 0; i < slots; i++)
	{
		Item* item = new Item();
		item->Init(ItemType::NONE);
		items.push_back(item);
	}
}

void PlayerInventory::SetItem(int slot, Item* item)
{
	items[slot] = item;
}

Item* PlayerInventory::GetItem(int slot)
{
	return items[slot];
}

void PlayerInventory::RemoveItemsOfType(ItemType type)
{
	for (int i = 0; i < slots; ++i)
	{
		if (GetItem(i)->GetType() == type)
		{
			Item* nullItem = new Item();
			nullItem->Init(ItemType::NONE);
			SetItem(i, nullItem);
		}
	}
}



What I have tried:

Thinking very hard about what to do but not knowing the answer so coming here for advice :)

解决方案

Use a smart pointer. Try, for instance

#include <iostream>
#include <vector>
#include <memory>
using namespace std;

class F
{
  int f;
public:
  F(int f):f(f) { cout<< "F(" << f << ") ctor called\n";}
  ~F() { cout << "F(" << f  << ") dtor called\n";}
};

int main()
{
  vector< F * > v;
  v.push_back(new F(1));

  vector < unique_ptr< F > > w;
  w.push_back( make_unique< F >(2) );
}


Output:

F(1) ctor called
F(2) ctor called
F(2) dtor called


Rule of thumb is, who creates memory has to delete it. So when you remove an vector you must delete the memory.

But you have the additional problem, that your vector may be copied or assigned somewhere deep in the vector implementation and so you may have 2 vectors with the same memory. Maybe it helps to overwrite these operators in which you copy the memory of the sourse vector.

I think you dont need to allocate the Item with new, but can use a typed vector.

std::vector<Item> myList;


I have found that yes, you do have to manually delete vectors of pointers. If you use Visual Studio and the DEBUG_NEW macro you will see the memory leaks in the debugger if you don't. At least, I do. I came up with this little template function a while ago to help with this situation :

// delete a vector of objects created with new

template< typename T >
void DeleteVector( std::vector<T> & v )
{
    size_t count = v.size();
    for( size_t n = 0; n < count; ++n )
        delete( v[n] );
    v.clear();          // just to be sure
}

If you use a malloc variant to allocate the pointers then you can make a variation of this function that calls free instead of delete and since free is not a typed operation the function does not need to be a template.


这篇关于使用std :: vector&lt; somepointer *&gt;管理内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆