我开始掌握指针并避免内存泄漏...如果存储在指针图中,是否需要删除对象?
虽然我有一个问题...在我开始之前,我没有使用C++ 11,所以请不要回复智能指针和信息,特定于C++ 11 ...
我有以下代码...
class Test
{
public:
Test(const int s_id, const std::string s_name) :
id(s_id),
name(s_name)
{
};
const int GetID()
{
return id;
}
private:
const int id;
const std::string name;
};
class TestCollection
{
public:
void AddTest(Test& my_test)
{
tests[my_test.GetID()] = &my_test;
}
void RemoveTest(const int id)
{
if (tests.find(id) != tests.end())
{
tests.erase(id);
}
}
public:
std::map<int, Test*> tests;
};
int _tmain(int argc, _TCHAR* argv[])
{
TestCollection collection;
Test my_test(0, "First Test");
collection.AddTest(my_test);
collection.RemoveTest(0);
return 0;
}
我的问题是,我需要做什么要清理我在调用RemoveTest时从my_test获取内存?为了避免内存泄漏?
我知道,当我使用新的关键字,我需要调用删除...但是我在这种情况下做什么?
它只是由垃圾收集器自动清理吗?
这取决于如何分配对象。但更好的发布实际代码。 – juanchopanza
该代码实际上不会编译。 'tests'只能存储指针,而你正在尝试存储一个引用。 –
您只需要'删除'用'new'分配的对象。在其他对象上使用'delete'是未定义的行为(我认为)。 – Florian