placement new and exception

Discussion in 'C++' started by wijhierbeneden, Oct 30, 2004.

  1. On
    in [16.9] In p = new Fred(), does the Fred memory "leak" if the Fred
    constructor throws an exception?
    there is this code:

    // Original code: Fred* p = new Fred();
    Fred* p = (Fred*) operator new(sizeof(Fred));
    try {
    new(p) Fred(); // Placement new
    } catch (...) {
    operator delete(p); // Deallocate the memory
    throw; // Re-throw the exception

    What exception can placement new throw???
    wijhierbeneden, Oct 30, 2004
    1. Advertisements

  2. Those thrown by constructor.

    Pavel Vozenilek, Oct 30, 2004
    1. Advertisements

  3. wijhierbeneden

    JKop Guest

    I don't recognize the syntax above.

    How about:

    Fred* p = reinterpret_cast<Fred* const &>( new char[sizeof(Fred)] );
    JKop, Oct 30, 2004
  4. it is valid to take an overloaded operator function, and access it
    directly. For example:

    myclass &operator +(myclass &a, myclass &b)

    myclass yy,zz ,ss;

    ss = operator +(yy,zz) ;

    is the same as:

    ss = yy + zz ;

    in rare circumstances this is useful...

    David Lindauer, Oct 30, 2004
  5. wijhierbeneden

    Old Wolf Guest

    JKop wrote on 27 Oct 2004 (4 days ago) in the thread
    titled "Your C++ Homework":
    If we throw the Standard Library out of the window for
    the moment, then I would be comfortable saying here that
    I'm an expert C++ programmer - I pretty much understand
    and know how to use all of the features of C++.
    Old Wolf, Oct 31, 2004
  6. wijhierbeneden

    JKop Guest

    Old Wolf posted:

    Am I the only one that finds this pathetic? Is it a lack of self-esteem
    that motivates you to ridicule others?

    JKop, Nov 2, 2004
  7. Probably.
    Bob Hairgrove, Nov 2, 2004
  8. And which ones??
    bad_alloc can't be thrown because there must not been allocated any memory.
    Can you give an example about an exception???
    wijhierbeneden, Nov 3, 2004
  9. Not necessarily. Placement new only suppresses the normal allocation for
    the object itself. If the object has pointer members, its constructor
    may attempt a normal allocation for whatever they point to, and that
    allocation may throw.
    Richard Herring, Nov 3, 2004
  10. wijhierbeneden

    Ron Natalie Guest

    ....or the constructors class members.
    Ron Natalie, Nov 3, 2004
  11. Indeed, recursively, ad infinitum. I just picked the simplest case.
    Richard Herring, Nov 3, 2004
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.