> Could you guys explain why pointers are bad?
Pointers aren't bad per se; in fact they are extremely useful. But they are also just more difficult to deal with than values. The idea is that our code becomes easier to reason about if we do not have to directly deal with pointers; their use is encapsulated.
This is easy to write, easy to understand, and easy to modify. We are looking at things from a high level of abstraction:
1 2 3 4 5 6 7 8 9 10
|
#include <iostream>
#include <string>
int main()
{
std::cout << "please type in your first name: " ;
std::string name ;
std::cin >> name ;
std::cout << "Hello " << name << '\n' ;
}
|
This program would not be feasible without a battery of pointers to back up the implementation.
std::cout internally holds a pointer to a stream buffer object.
It also has a locale object which in turn contains an associative array of reference-counted pointers to a dozen or so facet objects.
Some of these facets ...
std::string
too uses pointers internally;
std::cin >> name ;
requires careful management of those pointers.
In contrast, this is code with equivalent functionality where we decide to deal with pointers (just the ones that
std::string uses) ourselves. Brittle, error-prone code that is difficult to write and difficult to understand:
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 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
|
// adapted from 'Learning Standard C++ as a New Language' - Stroustrup
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
int main()
{
size_t sz = 20 ;
char* name = (char*)malloc(20) ;
if( name == NULL ) return 1 ;
puts( "please type in your first name: " ) ;
int c ;
while( ( c = getchar() ) != EOF )
{
if( !isspace(c) )
{
ungetc( c, stdin ) ;
break ;
}
}
size_t pos = 0 ;
while( ( c = getchar() ) != EOF )
{
if( isspace(c) )
{
name[pos] = 0 ;
break ;
}
name[pos] = c ;
if( pos == sz-1 )
{
sz *= 2 ;
char* temp = (char*)realloc( name, sz ) ;
if( temp == NULL )
{
free(name) ;
return 1 ;
}
else name = temp ;
}
++pos ;
}
printf( "Hello %s\n", name ) ;
free(name) ;
}
|
Notice how the simple logic of the program (ask for the first name, read it, print a hello message) is overwhelmed by low-level implementation details.