把指针放在std :: vector&内存泄漏

时间:2012-07-27 04:02:57

标签: c++ memory-leaks

class A {
public:
    void foo()
    {
        char *buf = new char[10];
        vec.push_back(buf);
    }

private:
    vector<char *> vec;
};

int main()
{
    A a;
    a.foo();
    a.foo();
}

class A中,foo()分配一些内存,指针保存到vec。当main()完成后,a将解构,a.vec也会解构,但是会释放分配的内存吗?

2 个答案:

答案 0 :(得分:4)

内存不会被释放。要将其发布,您需要将其放在unique_ptr或shared_ptr中。

class A {
   public:
     void foo()
     {
        unique_ptr<char[]> buf(new char[10]);
        vec.push_back(buf);
     }
   private:
     vector<unique_ptr<char[]>> vec;
};

答案 1 :(得分:2)

或者你可以制作一个析构函数

 ~A()
{
    for(unsigned int i =0; i < vec.size(); ++i)
         delete [] vec[i];
}

修改

正如所指出的,你还需要复制和分配(如果你打算使用它们)

class A
{
public:

    A& operator=(const A& other)
    {
        if(&other == this)
             return *this;

        DeepCopyFrom(other);

        return *this;
    }

    A(const A& other)
    {
        DeepCopyFrom(other);
    }


private:
    void DeepCopyFrom(const A& other) 
    {
        for(unsigned int i = 0; i < other.vec.size(); ++i) 
        {
            char* buff = new char[strlen(other.vec[i])];
            memcpy(buff, other.vec[i], strlen(other.vec[i]));
        }
    }

    std::vector<char*> vec;
};

更多关于深度复制的主题以及为什么需要它

http://www.learncpp.com/cpp-tutorial/912-shallow-vs-deep-copying/