Thread: new operator question

  1. #1
    Malum in se abachler's Avatar
    Join Date
    Apr 2007
    Posts
    3,195

    new operator question

    Implimenting a class, and I need new to return NULL if the contructor function encounters an error. Any ideas?

  2. #2
    Registered User
    Join Date
    Apr 2008
    Posts
    890
    Why not just throw from the constructor?

  3. #3
    Malum in se abachler's Avatar
    Join Date
    Apr 2007
    Posts
    3,195
    Im initializing a DirectShow filtergraph, so if it fails I need it to return a NULL pointer, so that the application doesnt try to use the failed class. More issues with supporting existing code that expects a NULL pointer on failure.

  4. #4
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,895
    No can do. nothrow new will return null on out-of-memory, but if the constructor throws an exception, it throws an exception.
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

  5. #5
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Im initializing a DirectShow filtergraph, so if it fails I need it to return a NULL pointer, so that the application doesnt try to use the failed class. More issues with supporting existing code that expects a NULL pointer on failure.
    You could initialise the filtergraph pointer to a null pointer constant, and then attempt to assign to it with new (possibly the nothrow version, or simply set the pointer to a null pointer constant in the catch block).

    EDIT:
    Oh yes, the nothrow version of new will not help, so you have to use try and catch anyway.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  6. #6
    Malum in se abachler's Avatar
    Join Date
    Apr 2007
    Posts
    3,195
    Aww bloody hell. I hate supporting code written by wankers. Thx anyway guys.

Popular pages Recent additions subscribe to a feed