-2
/ *
* \ brief Dictionary builder from file
*
* \ pre There is enough memory
* \ pre The file is first opened
*
* \ post If the file is open, the class instance has been initialized from
* from the dictionary file. Otherwise, we generate an empty class.
*
* \ exception bad_alloc if there is not enough memory
* This method calls chargeDicSyn!
* /
DicSyn::DicSyn(std::ifstream &file):
root(0), nbRadicals(0), groupesSynonymes()
{
    chargeDicSyn(file);
}

I have to throw the exception bad_alloc if there's not enough memory. I am really not an expert. How can I do it with this method?

Robert
  • 71
  • 1
  • 6
  • What do the function `chargeDicSyn` and the constructors of `root`, `nbRadicals` and `groupesSynonymes` do? – Ray Hamel Apr 04 '21 at 14:27
  • 4
    Throw it like any other exception? But generally, doesn't `new` and `new[]` already do so if there's "not enough memory"? What is the actual problem you have? – Some programmer dude Apr 04 '21 at 14:27
  • @RayHamel I had a little description of over the method definition – Robert Apr 04 '21 at 14:30
  • 1
    There is nothing in the posted code that directly allocated any heap memory. So the above code can not directly run out of heap. Please post a [mcve] ie some code that does directly allocate memory and as @RayHamel said `operator new` does this by default. – Richard Critten Apr 04 '21 at 14:32
  • *exception bad_alloc if there is not enough memory* -- If there is not enough to do what exactly? That comment lacks information on what exactly is allocating memory. Even then we need to see the code that actually allocates memory. – PaulMcKenzie Apr 04 '21 at 14:41

1 Answers1

1

If your code is using operator new (or anything that uses operator new, such as the standard library) to allocate memory, then it should already throw std::bad_alloc if there is not enough memory.

Edit: If it's using C-style memory management (malloc and friends), which I don't think it is, since you're constructing your object from a std::ifstream and not a FILE* like in C, then you should check if malloc returned nullptr (i.e. the pointer to which the call to malloc was assigned is null) and throw std::bad_alloc if it did. If for some reason you aren't able to do that, you could #include <cerrno> and check if errno == ENOMEM, although this is not quite as foolproof since malloc is not guaranteed to set errno on failure.

Ray Hamel
  • 1,289
  • 6
  • 16