2 Questions please help

My first question is that I am confused as to why in this program on line 18 bad_alloc has a & next to it. Even if I take that out it runs perfectly fine? If it is to make ex a reference why so?

Can anyone explain?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// Ex6_06.cpp
// Catching an exception thrown by new
#include<new>                    // For bad_alloc type
#include<iostream>
using std::bad_alloc;
using std::cout;
using std::endl;

int main( )
{
  char* pdata(nullptr);
  size_t count(~static_cast<size_t>(0)/2);
  try
  {
    pdata = new char[count];
    cout << "Memory allocated." << endl;
  }
  catch(bad_alloc& ex)
  {
    cout << "Memory allocation failed." << endl
         << "The information from the exception object is: "
         << ex.what() << endl;
  }
  delete[] pdata;
  return 0;
}



Here is my second question. In the function template why is len a const int reference? I removed it and it works fine but is there a specific reason? (line 9)

And also why is there a T before max when you already declared the return type in the angled brackets? (line 9)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// Ex6_08.cpp
// Using function templates
#include <iostream>
using std::cout;
using std::endl;
// Template for function to compute the maximum element of an array
template<typename T> T max(T x[], const int& len)
{
T maximum(x[0]);
for(int i = 1; i < len; i++)
if(maximum < x[i])
maximum = x[i];
return maximum;
}
int main(void)
{
int small[] = { 1, 24, 34, 22};
long medium[] = { 23, 245, 123, 1, 234, 2345};
double large[] = { 23.0, 1.4, 2.456, 345.5, 12.0, 21.0};
int lensmall(_countof(small));
int lenmedium(_countof(medium));
int lenlarge(_countof(large));
cout << endl << max(small, lensmall);
cout << endl << max(medium, lenmedium);
cout << endl << max(large, lenlarge);
cout << endl;
return 0;
}


Those were my questions. Thank you for helping.
Last edited on
1. The & is next to "ex", not "bad_alloc" - the programmer who wrote it just prefers the spacing to be that way for some reason. The reason it is there at all is because catching exceptions by reference is more efficient than catching them by value (and sometimes it is required).

2. I don't know why len is a const reference - this is poor design because primitives are passed faster by value than by reference, and passing by value is near-identical to passing by const reference.

As for the second part of that question, the return type is NOT the thing between the angled brackets. The "template<...>" part is the declaration for the template, it has nothing to do with a specific part of the function. The return type still needs to be specified, which is why the T is before the function name.
Last edited on
The Template<class t> determines what then? o.O

Also maybe it is because he doesnt want to modify len? But then why is it a reference. This makes no sense...
Last edited on
Anmol444 wrote:
The Template<class t> determines what then? o.O
It allows the type being dealt with to vary. They're called templates for a reason - you define the template, and the compiler uses that template to generate real functions that deal with the correct type.

http://www.cplusplus.com/doc/tutorial/templates/

Anmol444 wrote:
Also maybe it is because he doesnt want to modify len? But then why is it a reference f7. This makes no sense...
I think whoever wrote the code was unaware that it is better to pass primitives by value - they may be under the impression that passing by const reference is faster (it is for other types, but not for primitives).
Last edited on
oooh ok.

Also how does the compiler figure out the type to deal with?
The same way you would if you had to look at it manually. Templates are the 'smart' side of compilers, because so much stuff can be done for you by the compiler. It is called 'type deduction' and works almost like overload resolution. When it fails, you just have to specify the types manually e.g. max<TypeNameHere>(blah, blah, ...)
oo ok ty very much

Your like the most helpful person ever on this forum. You literally answer each and every one of my questions

I really appreciate it. Im 12 and trying to learn and its difficult. Thank you very much! :D
But I still dont understand exactly how a compiler can work this out. Is it useful information or should I just ignore it for now?
The compiler works it out at the point at which the code actually creates an object using the template. That's the point at which it knows what the type is. That's why, unlike for normal classes, you have to include the entire template definition in the header, including defining the contents of each method.

But, yeah, don't worry about what the compiler's doing. You're better off just trusting that it works, and focussing on learning to use C++.
Consider this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
template<typename T>
T ExampleFunc(T t)
{
    return t;
}

int main()
{
    char x = 'A';
    long double y = 3.1415926;
    std::cout << ExampleFunc(x) << std::endl
              << ExampleFunc(y) << std::endl
              << ExampleFunc<short>(x) << std::endl;
}
The compiler knows how to fill in the template parameters because it's pretty obvious. Passing x obviously means you only want to deal with type 'char', and passing type 'y' means you obviously only want to deal with type 'long double'. You can still specify otherwise though, as I did by specifying <short> for x.
Ok thank you :D
Topic archived. No new replies allowed.