function pointer

For the bad_alloc &. what does & do?
And for delet[] co, does it delete also the *ret in concat function?

#include <iostream>
#include <new> // bad_alloc
#include <string>
#include <cstdlib> // exit
using namespace std;

int * concat(const int arr0[], unsigned els0, const int arr1[], unsigned els1);

bool die(const string & msg);

void show(const int arr[], unsigned els);

int main() {
int ar0[]{ 1,2,3 }, ar1[]{ 4,5,6,7 };
int * co = concat(ar0, 3, ar1, 4);
show(ar0, 3);
show(ar1, 4);
show(co, 7);
delete[] co;
}

int * concat(const int arr0[], unsigned els0, const int arr1[], unsigned els1)
{
int * ret = nullptr;
try {
ret = new int[els0 + els1];
}
catch (const bad_alloc &) {
die("allocation failure");
}

for (unsigned i = 0; i < els0; i++)
ret[i] = arr0[i];
for (unsigned i = 0; i < els1; i++)
ret[els0 + i] = arr1[i];

return ret;
}

bool die(const string & msg)
{
cout << "Fatal error: " << msg << endl;
exit(1);
}

void show(const int arr[], unsigned els)
{
cout << "[" << els << "]:";
for (unsigned i = 0; i < els; i++)
cout << " " << arr[i];
cout << endl;
}
1
2
3
catch (const bad_alloc &) {
  die("allocation failure");
}

The thrown exception is catched as reference to const, rather than by value (i.e. copy).
(No different from the bool die(const string & msg);)

The handler does not use the exception and therefore the exception can be unnamed.

int * co = concat(ar0, 3, ar1, 4);
The 'co' is a pointer that stores the value returned by function.
The function returns the value of 'ret'.
The 'ret' is local to function and ceases to exist at the end of the function.

The 'delete' does not modify pointer object. It deallocates memory that is at address. The value of pointer is that address.
Topic archived. No new replies allowed.