Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overloading operator new and exception correctness

Tags:

c++

exception

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?

like image 869
Muxecoid Avatar asked Nov 02 '22 11:11

Muxecoid


1 Answers

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.

like image 51
ForEveR Avatar answered Nov 15 '22 04:11

ForEveR