Hello,
i've been studying c++ coding thanks to the preciuos contents of the forum; i have a question please.
i was wondering, what is the best/most used way to check that the required space has been successfully allocated, when this request is done dynamically.
I'm sure complex programs have much more advanced ways to perform this check, but can you please take a look at what i use below, if it's a way that can be considered efficiet/safe? or if you suggest a better one? looks like it works but wanted to ask for opinion. Thanks a lot.
#include <iostream>
using namespace std;
int main()
{
//....
int n;
cout << "enter size of array: ";
cin >> n;
cin.ignore();
int * pNumbers = new (nothrow) int[n];
if(pNumbers!=NULL)
cout << "Successfully reserved space for pNumbers. " << endl;
> what is the best/most used way to check that the required space has been successfully allocated,
> when this request is done dynamically.
The usual way is:
Use the normal (throwing) allocation function; to handle allocation failures, use a try/catch construct at the place where you know how to handle the failure.
It is also the best way; well written C++ code dies not have error handling code (try/catch) at places where we do not know how to handle errors.
Use std::nothrow only when a check for failure is required after every new. For instance, maintaining pre-1998 legacy code (on many implementations new returned a null pointer on allocation failure).
> You can't dynamically allocate the size of the array. You need to use something like std::vector.
The size of a dynamically allocated array can be determined at run time; but yes, ideally you would use a std::vector<> instead.