Difference between References and Pointers?

The code below does exactly the same thing. Which is better to use in terms of optimization? In what instances would you choose pointers instead of references; what instances would you choose references instead of pointers?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <string>
using namespace std;

void printRef(string &str) {
	cout << str << endl;
}

void printPnt(string *str) {
	cout << *str << endl;
}

int main() {

	string myString = "Hello World";

	printRef(myString);
	printPnt(&myString);

	cin.get();
	return 0;
}
I would use references wherever I can, and avoid pointers wherever I can.

I think that a feature that you're not using is more important for these functions, namely const qualifying your variables, since these functions shouldn't modify the strings.

They don't do exactly the same thing.

Optimization of what? Speed, size, maintainability, etc?

From the point of view of the caller, there is a clear difference (and possibility):
1
2
3
4
5
int main() {
  printPnt( nullptr ); // syntactically correct
  printRef( /*nothing*/ ); // impossible
  return 0;
}

In other words a reference is always to a valid object, but the pointer can be valid, invalid or to an element in an array.


In void printPnt(string *str); the str is a by value parameter, a separate variable that requires space (memory for one address). A reference is not a variable.
The code below does exactly the same thing. Which is better to use in terms of optimization?
References are easier to use and does not produce garbage looking code. Optimisaton-wise both are usually equivalent. References might have and edge over pointers in theory, nowever I never seen it in practice, usually compilers are smart enough to optimise pointer access as they do wiht references.

In what instances would you choose pointers instead of references
When you need to rebind it (references are not rebindable) or point to nothing (there is no such thing as null reference)

what instances would you choose references instead of pointers?
Anywhere where I not reqired to use pointers. Have to do so if I want to pass temporary objects.

BTW, your code is not const correct. Fixed code and example of reference-only semantic:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <string>

void printRef(const std::string& str) 
{
	std::cout << str << '\n';
}

void printPnt(const std::string* str) 
{
	std::cout << *str << '\n';
}

int main() 
{
	std::string myString = "Hello World";
	//Possible with const references: creating temporary std::string from string literal and passing it
	printRef("Hello World"); 

	//Try to do that with pointers and without memory leaks
	printPnt(&myString);
}

Last edited on
Topic archived. No new replies allowed.