I am using c++ constant value std::nothrow in new operator to avoid exception on failure, and return a null instead. But as I tried, this seems not work on my environment is g++ 4.4.4 on Linux x86_64.
Following is the testing program and execution result:
#include <stdlib.h>
#include <new>
#include <iostream>
class TT {
public:
TT(int size);
~TT();
private:
char * buffer;
};
TT::TT(int size) : buffer(NULL) {
if (size <= 0) {
throw std::bad_alloc();
}
buffer = (char *)malloc(size);
if (buffer == NULL) {
throw std::bad_alloc();
}
}
TT::~TT() {
if (buffer != NULL) {
delete buffer;
}
}
int main(int argc, char * argv[]) {
TT * tt = NULL;
try {
tt = new TT(0);
} catch (std::bad_alloc& ba) {
std::cout << "tt exception caught" << std::endl;
}
tt = new (std::nothrow) TT(0);
if (tt == NULL) {
std::cout << "tt is null" << std::endl;
}
else {
std::cout << "tt is not null" << std::endl;
}
return 0;
}
Execute result:
$ uname -i
x86_64
$ g++ --version
g++ (GCC) 4.4.4 20100726 (Red Hat 4.4.4-13)
Copyright (C) 2010 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
$ g++ t.cpp
$ ./a.out
tt exception caught
terminate called after throwing an instance of 'std::bad_alloc'
what(): std::bad_alloc
Aborted
From the output message, there is an exception thrown; but I wish it should not, instead a null pointer return is expected. Can anybody help me with this issue. Thanks.
Of course there's a std::bad_alloc
thrown. Your own code throws it.
new (std::nothrow)
only specifies that the memory allocator of the new expression won't throw. But once your TT
object is being constructed in that memory, it may still throw any exception it likes.