最好的方法来删除一个向量指针? [英] best way to delete a vector pointer?

查看:139
本文介绍了最好的方法来删除一个向量指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

如何正确删除指针?


std :: vector 将一组对象放入其中供以后使用,我使用 DETAIL * pPtr = new DETAIL 创建指针,然后将其插入向量。



DETAIL的结构

  struct DETAIL {
int nRef;
short sRandom;
};这是在向量中删除和删除指针的最好方法

  while(Iter1!= m_Detail.end())
{
if((* Iter1) - > nRef == m_SomeVar)
{
delete * Iter1;
m_Detail.erase(Iter1);
break;
}

Iter1 ++;
}


解决方案

转换为向量,而是使用智能指针,如 std :: shared_ptr 。然后,不需要 delete ,只需擦除指向向量,并且指向的对象将被自动删除。


Possible Duplicate:
how to properly delete pointer?

i'm using std::vector to put a group of objects into it for later use, i am using DETAIL* pPtr = new DETAIL to create the pointer, and then inserting it into the vector.

the struct of DETAIL

struct DETAIL {
    int nRef;
    short sRandom;
};

Is this the best way to delete and erase a pointer within a vector leaving no room for memory leaks?

while(Iter1 != m_Detail.end())
{
    if((*Iter1)->nRef == m_SomeVar)    
    {
        delete  *Iter1;
        m_Detail.erase(Iter1);
        break;
    }

    Iter1++;
}

解决方案

Don't put raw pointers into the vector, instead use smart pointers such as std::shared_ptr. Then there is no need for delete, simply erase the pointer from vector and the pointed object will be automatically deleted.

这篇关于最好的方法来删除一个向量指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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