Yes, hkmixxa, that is closer. If you want to throw an exception, you still have to throw an exception. As I mentioned earlier, and as Kybo_Ren's examples show, new should already throw an exception if it fails, so his second example would be completely fine. If new failed, it would immediately stop in the middle of the function and the exception would be thrown.
However, some compilers don't work correctly when new fails. They return 0 (or NULL) instead of throwing an exception. If you aren't sure which one your compiler does, you can code like this:
Code:
dynamicInt::dynamicInt(const dynamicInt& obj)
{
ptr = new int;
if(ptr == 0)
throw std::bad_alloc();
*ptr = obj.getData();
}
You can also test which way your compiler reports the error with this code:
Code:
#include <iostream>
#include <limits>
int main()
{
try
{
double* p = new double[std::numeric_limits<int>::max()];
if (p != 0)
{
std::cout << "Memory allocation succeeded. Increase allocation size!" << std::endl;
return EXIT_FAILURE;
}
std::cout << "2. Returned null pointer on failure." << std::endl;
}
catch(const std::bad_alloc& )
{
std::cout << "1. Threw bad_alloc exception on failure." << std::endl;
}
catch(...)
{
std::cout << "Some other exception was thrown!" << std::endl;
}
return EXIT_SUCCESS;
}
If it outputs 1, then you can use Kybo_Ren's second example and allow new to throw the exception for you. If it outputs 2, then you must check the return of new for against 0 (or NULL).