Thread: Deleting an object if the constructor failed.

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #1
    In the Land of Diddly-Doo g4j31a5's Avatar
    Join Date
    Jul 2006
    Posts
    476

    Deleting an object if the constructor failed.

    Hi guys, I want to ask you about how to delete an object if its constructor failed to initialize one of its members. I tried it like below but failed:

    Code:
    B* A:CreateB(std::string paramStr)
    {
        B* pB= NULL;
        try
        {
             pB = new pB (paramStr);
        }
        catch (int result)
        {
             if (result == OK) // OK == 1
             {
                    m_VectorB.push_back(pB);
             }
              else if (result == FAILED)
             {
                    delete pB;
                    pB = NULL;
             }
        }
        return pB;
    }
    
    B::B(std::string paramStr)
    {
        int result = initMembers (paramStr); //returns OK / 1 if successful or FAILED / 0 if failed
        throw result ;
    }
    Now, FYI, I have never ever ever used exception in my entire life as a programmer. All my error handlings are either by return value or assertion. I know that it is not a good habit but I still don't have a good understanding about it. So, how can I solve this problem? Thanks in advance.
    Last edited by g4j31a5; 09-15-2009 at 01:54 AM.
    ERROR: Brain not found. Please insert a new brain!

    “Do nothing which is of no use.” - Miyamoto Musashi.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Deleting object after list removal (C++ visual studio)
    By RancidWannaRiot in forum Windows Programming
    Replies: 2
    Last Post: 10-20-2005, 06:06 PM
  2. Question on l-values.
    By Hulag in forum C++ Programming
    Replies: 6
    Last Post: 10-13-2005, 04:33 PM
  3. A question about constructors...
    By Wolve in forum C++ Programming
    Replies: 9
    Last Post: 05-04-2005, 04:24 PM
  4. deleting dynamic object problem
    By eth0 in forum C++ Programming
    Replies: 17
    Last Post: 05-19-2004, 01:17 PM
  5. Array of Pointers + Deleting An Object = Problems
    By Nereus in forum C++ Programming
    Replies: 3
    Last Post: 03-04-2004, 12:16 PM