Two simple questions: In plain C we frequently use xmalloc which is a allocate-or-abort routine. I implemented it in C++. Is this a right exception-free implementation?
template <typename T>
T *xnew(const size_t n)
{
T *p = new (std::nothrow) T[n];
if (p == nullptr)
{
cerr << "Not enough memory\n";
abort();
}
return p;
}
int main()
{
int *p = xnew<int>(5000000000LL);
}
Second question, if I remove the <int> from the xnew<int>(5000000000LL); call, compiler (g++ 4.7.2) cannot infere that [T = int] anymore although the return type int * is still there. Why is that?
Edit: Isn’t there any overhead when using the new version which could throw exception even if it’s not thrown? I really don’t want to use any exceptions when not absolutely necessary.
I fail to see why this is necessary.
newwill throwstd::bad_allocif it fails to allocate memory. If you don’t handle exceptions, this
will lead to a call to
std::terminatewhich effectively ends theprogram and has the same behavior as
xmalloc.Of course, this changes when your compiler does not implement exceptions.