Is this proper usage of pointers?

Hey everyone! I was wondering if I properly used pointers correctly with this function template to swap the type's. I mean it works but did I do it in the most proper way? Any way to improve will be helpful to know thank you!

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
#include <iostream>

using namespace std;

//Function template
template <class T>
void swapType (T *first, T *second) {
	T temp;
	temp	=	*first;
	*first	=	*second;
	*second	=	temp;
}

int main()
{
	int a = 1, b = 2;

	cout << "Before swapNumbers (a, b) : " << endl;
	cout << "a = " << a << endl;
	cout << "b = " << b << endl;

	swapType (&a, &b);

	cout << "After swapNumbers (a, b) : " << endl;
	cout << "a = " << a << endl;
	cout << "b = " << b << endl;
	return 0;
}
Yes, I think it can be used although there is also a different way ..like using the reference as
1
2
3
4
5
6
7
template <class T>
void swapType (T &first, T &second) {
	T temp;
	temp	=	first;
	first	=	second;
	second	=	temp;
}
@Ryan Wilson: The danger with using pointers is the possibility that one (or both) of them will be NULL (not in your example, but in the general case) -- instant segfault and lots of debugging required. This is the advantage of using bluecoder's reference suggestion - it also removes the need to remember to pass the address of the objects (although this may or may not be an advantage, depending on your opinion on explicitness).
Topic archived. No new replies allowed.