2

I see a lot of C++ libraries dealing with dynamic memory allocation this way:

Qimage* _image = new QImage(width, height, QImage::Format_RGB888);
if (!_image)
{ 
    // Failed!
}

I find it interesting that it is possible to check whether an object was succesfully allocated or not with a simple code like if (!_image).

1) I wonder if this is a native feature of the standard new or if this is only possible if you overload operator new with your own implementation.

2) How would I go about implementing operator new in this case, where it receives arguments for the object's constructor and it returns NULL in case width && height are 0?

Did I get any of this right?

karlphillip
  • 92,053
  • 36
  • 243
  • 426
  • Indeed, fixed! Thanks @James. – karlphillip Dec 08 '11 at 18:54
  • To be honest, it seems weird that the return value of new would be based on the quality of the parameters. I would personally expect either a) the constructor to throw an exception on bad input, or b) to create a function that checks the parameters and returns 0 if the input is malformed....but that's just me. – riwalk Dec 08 '11 at 18:57
  • That's essentially what I was interested in doing. – karlphillip Dec 08 '11 at 19:08

1 Answers1

4

What you see is wrong. new doesn't return null anymore but throws std::bad_alloc instead

Overloading new has an example. You don't need to deal with constructor arguments

What you are trying to do is done kindof by make_shared in C++11

Community
  • 1
  • 1
parapura rajkumar
  • 24,045
  • 1
  • 55
  • 85
  • But an overloaded `operator new` could do what I'm proposing, right? – karlphillip Dec 08 '11 at 18:55
  • Yes, it could. But new don't get the arguments to constructor. It is called before the constructor. – Basile Starynkevitch Dec 08 '11 at 18:56
  • I don't think an overloaded operator new is allowed to return null unless it is nothrow (or in C++11, has a throw() specification). There may be other cases, but I'm pretty sure plain old new is never allowed to return null. – James McNellis Dec 08 '11 at 19:33