简体   繁体   中英

put pointer in std::vector & memory leak

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();
}

In class A , foo() allocates some memory and the pointer is saved to vec . When main() finishes, a will desconstruct, and so will a.vec , but will the allocated memory be released?

The memory will not be released. For it to be released, you need to put it in either a unique_ptr or a shared_ptr.

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

Or you could make a destructor

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

EDIT

As pointed out you need to make copy and assignment also (if you intend to use them that is)

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;
};

More on the subject of deep copying and why you need it here

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM