Can I call a new instance of the C ++ class if certain conditions in the constructor are not met?

As I understand it, when a new instance is created in C ++, a pointer to a new class is returned, or NULL if there is not enough memory. I am writing a class that initializes a linked list in a constructor. If an error occurred while initializing the list, I would like the class instance to return NULL.

For instance:

MyClass * pRags = new MyClass;

If the linked list in the MyClass constructor cannot be initialized correctly, I would like pRags to be NULL. I know that I can use flags and additional checks for this, but I would like to avoid this if possible.
Does anyone know a way to do this?

+5
source share
3 answers

The general approach here is to throw an exception (and handle it somewhere above).

One of the advantages of the exception mechanism is that it allows you to raise an exception from the constructor of the class. In this case, you will never get to the situation where the pointer returns invalid. You must "get control" in the appropriate catch block. If the pointer was declared only in the try block (or in some other method called by the try block), it will be outside your scope in this catch block.

- . , (, ), , , .

( Java 10 , ++ , , , , - )

// Begin C++ code written by a Java programmer... :)
class Myclass
{
   public:
      Myclass(int length)
      {
          if(length<=0) throw BadBufferSizeException("Bla bla bla");         
          this->buffer = (char*)malloc(length*sizeof(char)); // don't remember the new syntax
      }

      void doSomething()
      {
          // Code for placing stuff in the buffer
      }
    private:
      char* buffer;
};


int main()
{
   try
   { 
     int len;
     len = getLengthFromUser();
     MyClass* pMyClass = new MyClass(len);
     myClass->doSomething();
    } catch(const Exception & e)
    {
       // Whatever... Note how pMyClass is not even accessible here
    }
}

, pMyclass null try, try , , , , -(). , doSomething() try-catch, , .

, ++ ( ?) , , . .

+16

.

- NULL, factory, ...

class MyClass
{
    public:
        static MyClass* makeMyClass()           
        {
           MyClass* retval = NULL;
           try 
           {
              retval = new MyClass();
           }
           catch(std::exception& e)
           {
               // Report the exception;
               retval = NULL;
           }
           return retval;
       }
    // ....
    };
+1

Your understanding is somewhat outdated as the Standard in 1995 was ordered to use exceptions instead of returning 0. It also provides a number of methods nothrow, which work as follows: Foo * foo = new (nothrow) Foo;.

0
source

All Articles