stefan
stefan

Reputation: 10355

c++ destructors - when to use them and what is to be deleted

I'm having a hard time with current project. In previous versions I used std::vectors and all went fine, no memory leaks, no errors, just fine.

Then I switched to use some pointers since it's just more elegant and I have improved performance a bit.

So I have classes like

class A
{
    private:
        std::string str;
    public:
        A() {str = "";}
};

class B
{
    private:
        std::string str;
        A* a;
    public:
        B() {str = ""; a = NULL; }
};

class C
{
    private:
        std::vector<B*> bs;
    public:
        C() { bs = std::vector<B*>(); }

};

I know that every time I use new, I have to delete it afterwards. So I create destructors for class B and class C.

That's what I think it should look like:

B::~B()
{
    if ( this->a != NULL )
        delete this->a;
}

C::~C()
{
    while ( (this->bs).size() > 0 )
    {
        if ( (this->bs).back() != NULL )
            delete (this->bs).back();
        (this->bs).pop_back();
    }
    (this->bs).clear(); // not necessary since bs has size 0?
}

But with that, I'm getting various errors, such as "Invalid read of size 4" in valgrind.

Is my idea of what destructors should look like ok? What else could be problematic with my code? Would it be good to change the private std::string members to std::string-pointers? Is it necessary or a good thing to do str = ""; in destructors?

On a side note: Please understand that I have done a lot of searching on "proper destructors" and similar keywords and it just didn't help. If you think this was asked too often: I don't, because I don't get it.

Upvotes: 1

Views: 186

Answers (1)

Andreas Brinck
Andreas Brinck

Reputation: 52549

What Rob said, and also your destructors can be simplified to:

B::~B()
{
    delete a;
}

C::~C()
{
    for (size_t i = 0; i < bs.size(); ++i)
        delete bs[i];
}

Upvotes: 1

Related Questions