Page 1 of 1

[C++] Cum semnaleaza eroare operatorul standard 'new'?

Posted: 22 Mar 2009, 13:14
by Ovidiu Cucu
Intrebare Cum semnaleaza eroare operatorul standard 'new'?

Raspuns
In headerul standard <new> sunt declarate urmatoarele functii pentru alocare dinamica:
  1. Code: Select all

    void* operator new(std::size_t size) throw(std::bad_alloc);
  2. Code: Select all

    void* operator new(std::size_t size, const std::nothrow_t&) throw();
  3. Code: Select all

    void* operator new[](std::size_t size) throw(std::bad_alloc);
  4. Code: Select all

    void* operator new[](std::size_t size, const std::nothrow_t&) throw();
In caz de eroare (operatorul new nu reuseste sa aloce memoria ceruta)...
  • ...(1) si (3), arunca exceptii de tip bad_alloc.
    Exemplu

    Code: Select all

    #include <iostream>
    int main()
    {
       try
       {
          // try to allocate a large amount of memory; if fails, 'new' throws an exception.
          char* buffer = new char[0x7ffffffe];
          std::cout << "Allocation succeeded." << std::endl;
          delete []buffer;
       }
       catch(std::bad_alloc& e)
       {
          // handle standard bad_alloc exception.
          std::cout << "Exception: " << e.what() << std::endl;
       }
    }
  • ...(2) si (4) nu arunca exceptii, in schimb intorc un pointer NULL.
    Exemplu

    Code: Select all

    #include <iostream>
    int main()
    {
       // try to allocate a large amount of memory; if fails, 'new' returns a NULL pointer.
       char* buffer = new (std::nothrow) char[0x7ffffffe];
       if(NULL == buffer)
       {
          std::cout << "Allocation failed." << std::endl;
       }
       else
       {
          std::cout << "Allocation succeeded." << std::endl;
          delete []buffer;
       }
    }

Next FAQ >>

Re: [C++] Cum semnaleaza eroare operatorul standard 'new'?

Posted: 22 Mar 2009, 14:24
by Viorel
NOTE:
  • Cu ajutorul funcţiei _set_new_handler poate fi instalată o procedură care să elibereze memoria şi să reîncerce alocarea eşuată.

Next FAQ >>

Re: [C++] Cum semnaleaza eroare operatorul standard 'new'?

Posted: 08 May 2009, 14:14
by Ovidiu Cucu
O alternativa la apropunerea lui Viorel este sa se combine cele doua versiuni de 'new'.

Code: Select all

   try
   {
      // if first allocation attempt fails 'new' returns a NULL pointer
      char* buffer = new (std::nothrow) char[size];
      if(NULL == buffer)
      {
         // do some cleaning if possible and/or compact the heap, then try again.
         // ...
         ::HeapCompact(::GetProcessHeap(), 0);
         // in case of failure (this time, it's really bad) an exception is thrown.
         buffer = new char[size];
      }
      // ...
   }

Next FAQ >>