0

I am trying to handle situations where the constructor of an object can fail to allocate memory to some of its dynamically allocated members. How can I do this without exceptions?

eg:

A::A()
{
    mem1_ = new Member1();
    if (mem1_ == NULL) {
        delete this;
        return;
    }
}
B::B()
{
    a1 = new A();
    if (a1 == NULL) {
        delete this;
        return;
    }
}

Is this code block allowed? It is compiling.

siri
  • 123
  • 1
  • 13
  • 2
    How could you possibly use this? You do, say, `A* foo = new A;` -- then how do you know whether you can use `foo` or not? You have a pointer that may or may not be to an object -- what can you do with it?! – David Schwartz Mar 15 '17 at 21:36
  • 1
    Why in the world would you want to do that?? What if the object is created as an object of *automatic storage duration*?, There are so many open questions.... In the end its most likely going to be a really bad idea.... – WhiZTiM Mar 15 '17 at 21:37
  • if you seriously need to not use exceptions, a) have fun not using the standard library and losing RAII, because b) construct, then initialize – jaggedSpire Mar 15 '17 at 21:37
  • Whatever it is you are trying to do, and it's not clear what that is, this is not the way. Either use exceptions or use an object that has an "invalid" state that callers can check for and then they discard the object. – David Schwartz Mar 15 '17 at 21:38
  • Okay, will try to avoid this scheme. Will a new operator return NULL if an object can't be allocated completely? Like if a member couldn't be allocated within the constructor. – siri Mar 15 '17 at 21:53
  • @siri By default new throws an exception if it can't allocate. See nothrow http://en.cppreference.com/w/cpp/memory/new/nothrow if you don't want this (but you almost certainly do). –  Mar 15 '17 at 22:05

0 Answers0