0

This is for a school project, so no need to ask details as to why I'm using an array of lists (I'm supposed to make a custom HashMap without using unordered map). My question is, when creating this array in the constructor (the array also needs to be allocated using dynamic memory), what happens in the case it couldn't allocate memory and "new" fails? Since each list is allocated on the heap, does that mean that it could fail midway, and there could be memory leakage?

Example:

class A
{
private:
    std::list<std::string> * a;
public:
    A() : a(nullptr)
    {
        a = new std::list<std::string>[10]; 
    }
};

So for example, could this fail midway while creating the lists, which will cause memory to leak? If so, how would I use nothrow in this case? How do I know where it stopped and failed? Should I initialize each list independently?

NGneer
  • 23
  • 4
  • 5
    One almost *never* need a pointer to a container. What is the reason you use a pointer to a list? What is the problem that's supposed to solve? Why not a vector of lists (`std::vector>`)? – Some programmer dude Sep 12 '20 at 10:48
  • 1
    As for what happens when `new` fails, any [decent book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list/388282#388282), tutorial or class should have information about that. – Some programmer dude Sep 12 '20 at 10:51
  • Because these were the given instructions - "use a dynamically allocated array to hold the buckets". The data structure for the buckets is up to us though. I know what happens when new fails, what I don't understand is if this could cause memory to leak if it fails midway creating the lists. As in, what happens if one of the lists fails? – NGneer Sep 12 '20 at 12:01
  • [How should I handle resources if my constructors may throw exceptions?](https://isocpp.org/wiki/faq/exceptions#selfcleaning-members) (Especially note "If a constructor throws an exception, the object’s destructor is *not* run.") – Some programmer dude Sep 12 '20 at 12:37
  • Also, if `new` fails and throws an exception, no memory will have been allocated. – Some programmer dude Sep 12 '20 at 12:37
  • 1
    @NGneer for a "dynamic allocated array to hold the buckets" I recommend instantiating a `std::vector>>` rather than using `new` and `delete`. The `std::vector` will do the necessary `new` and `delete` operations for you, and you won't have to worry about memory leaks. (and don't worry, the array is still dynamically allocated even if you aren't allocating it yourself!) – Jeremy Friesner Sep 12 '20 at 14:10

0 Answers0