STL erase-remove idiom vs custom delete operation and valgrind

This is an attempt to rewrite some of the old homework using STL algorithms instead of hand loops and much more.

I have a class called Database that contains Vector<Media *>where Media * can be (among other things) a CD or book. The database is the only class that processes dynamic memory, and when the program starts, it reads a file formatted as shown below (somewhat simplified), allocating space when it reads records, adding them to the vector (v_) above.

CD
Artist
Album
Idnumber
Book
Author
Title
Idnumber
Book
...
...

, , : EDIT: , , " " . , - , find_if , . /EDIT.

typedef vector<Media *>::iterator v_iter;

...
void Database::removeById(int id) {
    v_iter it = find_if(v_.begin(), v_.end(), Comparer(id));
    if (it != v_.end()) {
        delete *it;
        v_.erase(it);
    }
}

- true, , , . , valgrind , STL, -, -

void Database::removeById(int id) {
    v_.erase(remove_if(v_.begin(), v_.end(), Comparer(id)), v_.end());
};

, , "", valgrind, ? , - - 3 allocs 'not freed' Media, .

+3
7

. , , , , , , . , , .

+3

: remove() , , .

" STL" Scott Meyers. ! , -, .

( , . 33). , isCertified() false.

class Widget
{
  public:
    isCertified() const;
  ...
};

void delAndNullifyUncertified(Widget*& pWidget)
{
  if (!pWidget->isCertified())
  {
    delete pWidget;
    pWidget = 0;
  }
}

vector<Widget *> v;
v.push_back(new Widget);
...
// set to NULL all uncertified widgets
for_each(v.begin(), v.end(), delAndNullifyUncertified);
// eliminate all NULL pointers from v
v.erase(remove(v.begin(), v.end(), static_cast<Widget *>(0)),
        v.end();

, .

(28 2012 .): Slavik81

+4

delete *it. ... v_.erase - - , , .

+3

. , . , .
std::vector<std::shared_ptr<Media> >, .

( std::shared_ptr, , , std::tr1::shared_ptr. boost boost::shared_ptr.)

+2

removeById delete. delete .

- removeById, :

void Database::removeById(int id) {
    v_iter it = find_if(v_.begin(), v_.end(), Comparer(id));
    if (it != v_.end()) {
        //delete *it;
        v_.erase(it);
    }
}

, , , .

+1

, vector , .

, STL OO , . .

- (, ) . shared_ptr, ++ 0x, unique_ptr.

, . , STL, . (), , ( shared_ptr).

Boost Pointer Container

, , , .

, ( , ) STL, erase/remove, find_if ..

+1

, . , shared_ptr:

typedef vector <shared_ptr <Media>> MediaVector;
...
0
source

Source: https://habr.com/ru/post/1755189/


All Articles