Antwort: [AGENT++] SNMP++/Agent++ on Windows (VC++) and the new operator

Jens Engel Jens.Engel at marconi.com
Fri Feb 25 13:46:02 CET 2005


Another note to Marek's comments:

> I would like to warn SNMP++ and Agent++ Windows users who build
applications with Visual C++ as it seems that by
> default, the new operator throws an std::bad_alloc exception (new C++
standard compliant approach) rather than
> returning null (the old-good (?) C++) when the heap is exhausted.
...
> Please refer to this manual section for details - it is even easier to
enforce exceptions, although this breaks
> SNMP++ (as it is written in the old fashion).

Well, the core problem is not that SNMP++ checks for NULL pointers after
new() (if you meant that).
I wouldn't use a try-catch block for std::bad_alloc in most places were
objects are allocated.
The core problem is that SNMP++/Agent++ does not use an exception-safe
programming style [1, 2] (in most cases).
NOTE: Exception-safe does not mean that you use try-catch in all places,
      but to ensure that you do not leak resources (as memory, ...) and
      that program might continue running.

IMHO, there are (at least) 2 problems:
  * MIB or MIB objects remain locked when an exception is thrown and not
caught.
    SOLUTION: Use ScopeGuards (ala Lock) instead of manually
locking/unlocking at critical sections.
    Note that ScopeGuards may have an dismiss() method that allows the user
to manually perform unlock() [3].

  * Memory in call-chain is leaked, because objects are assigned to
pointers
    (and not cleaned up when exception is thrown).
    SOLUTION: Use ScopeGuards ala std::auto_ptr or boost::scope_ptr.


SEE ALSO:
[1] Bjarne Stroustrup, "Programming with Exceptions",
http://www.informit.com/articles/article.asp?p=21084&seqNum=5

[2] Herb Sutter, "Exceptional C++",
http://www.gotw.ca/publications/xc++.htm (on exception safe programming
styles)
  "Exception-Safe Class Design, Part 1: Copy Assignment":
http://www.gotw.ca/gotw/059.htm

[3] Andrei Alexandrescu, Petru Marginean, "Generic<Programming>: Simplify
Your Exception-Safe Code" (ScopeGuard concept),
     C/C++ User Journal, December 2000.
http://www.cuj.com/documents/s=8000/cujcexp1812alexandr/alexandr.htm

Sincerely,
Jens Engel

P.S.: Just an idea to "reverting to the nothrow new allocation scheme".
Most C++ compilers allow to disable exceptions.
I would assume that no std::bad_alloc is thrown when exceptions are
disabled (and hopefully a NULL pointer is returned).
But I have not checked it.

mailto:Jens.Engel at marconi.com







More information about the AGENTPP mailing list