Reputation: 1241
While looking at legacy code I found something similar to the following code
void* legacy_type::operator new(size_t size) {
return pool_alloc(size);
}
pool_alloc is known to never throw and return 0 in case of failure.
There is no overload for std::nothrow variant of new here.
I wonder whether this code is semantically correct and has well defined behavior.
Should new (std::nothrow) legacy_type;
use custom pool_alloc? In my compiler it does not compile at all. Is it well defined behavior?
Should constructor run and crash due to this==0
if overloaded operator new
returns zero? In my compiler it runs (and crashes on member initialization). Is it standard well defined behavior?
Upvotes: 5
Views: 231
Reputation: 55887
1) No it shouldn't. These are different functions. And, when you overload one of the operations - all other operations will never work, if they are not overloaded, since if there is operator new
in class-scope and signature is not acceptable, then compiler will not search for global operator new
, so, compile-error will happened.
2) You break postconditions, if your new
will return null pointer.
n3376 18.6.1.1/3
Required behavior: Return a non-null pointer to suitably aligned storage (3.7.4), or else throw a bad_- alloc exception. This requirement is binding on a replacement version of this function.
If you want to returns 0, you should use following signature
void* operator new(size_t) throw()
if you use this overloading and returns 0 from it, there is no seg-fault.
n3376 5.3.4/13
If the allocation function returns null, initialization shall not be done, the deallocation function shall not be called, and the value of the new-expression shall be null.
Upvotes: 2