2015-10-25 63 views
-1

我开始掌握指针并避免内存泄漏...如果存储在指针图中,是否需要删除对象?

虽然我有一个问题...在我开始之前,我没有使用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获取内存?为了避免内存泄漏?

我知道,当我使用新的关键字,我需要调用删除...但是我在这种情况下做什么?

它只是由垃圾收集器自动清理吗?

+0

这取决于如何分配对象。但更好的发布实际代码。 – juanchopanza

+1

该代码实际上不会编译。 'tests'只能存储指针,而你正在尝试存储一个引用。 –

+1

您只需要'删除'用'new'分配的对象。在其他对象上使用'delete'是未定义的行为(我认为)。 – Florian

回答

1

在该示例中,collection和my_test都分配在堆栈上。一旦范围结束(从_tmain返回),内存将被释放。

将可能存在于变量作用域之外的堆栈变量的指针引起不可预知的行为。在这种情况下,如果集合获取对象并存储指针而不是副本。

+0

什么是替代方案?要改用指针到处? – Ricky

+0

您可以让TestCollection类创建要传递的对象的副本。该副本将驻留在堆中,并将使用新的副本进行分配。 当调用Remove时,您需要删除它。调用者不需要使用指针。 – Imran

+0

你能澄清你的意思是来电者吗? – Ricky

相关问题