-1

I want to do something like this:

std::set<my_type*> s;

s.insert(new my_type(...));
...
s.erase(...);

Where the set's erase will delete the pointer to avoid a memory leak.

Is this possible with C++ containers or would the proper solution be to subclass the container and write my own erase, or use some sort of smart pointer scheme?

user318904
  • 2,968
  • 4
  • 28
  • 37

1 Answers1

6

Your set is declared to store my_type, but you're sending it my_type*, so the code is inconsistent as is. In any event, if you don't need heap allocation, don't use it:

std::set<my_type> s;

// Emplace improves on s.insert(my_type(...)); by allowing construction in place
// to minimize move/copy work
s.emplace(...args for my_type...);
...
s.erase(...);

With no heap allocation, your my_type destructor is called and no delete is needed for its own structure (or more precisely, set manages that internally).

If you need heap allocation, use smart pointers so deletion implies freeing (and std::make_unique makes this cleaner and lets you completely avoid all use of new and delete):

std::set<std::unique_ptr<my_type>> s;

s.insert(std::make_unique<my_type>(...));
...
s.erase(...);
Community
  • 1
  • 1
ShadowRanger
  • 143,180
  • 12
  • 188
  • 271