What's so bad about pointers in C++?
- by Martin Beckett
To continue the discussion in Why are pointers not recommended when coding with C++
Suppose you have a class that encapsulates objects which need some initialisation to be valid - like a network socket.
// Blah manages some data and transmits it over a socket
class socket; // forward declaration, so nice weak linkage.
class blah
{
... stuff
TcpSocket *socket;
}
~blah {
// TcpSocket dtor handles disconnect
delete socket; // or better, wrap it in a smart pointer
}
The ctor ensures that socket is marked NULL, then later in the code when I have the information to initialise the object.
// initialising blah
if ( !socket ) {
// I know socket hasn't been created/connected
// create it in a known initialised state and handle any errors
// RAII is a good thing !
socket = new TcpSocket(ip,port);
}
// and when i actually need to use it
if (socket) {
// if socket exists then it must be connected and valid
}
This seems better than having the socket on the stack, having it created in some 'pending' state at program start and then having to continually check some isOK() or isConnected() function before every use.
Additionally if TcpSocket ctor throws an exception it's a lot easier to handle at the point a Tcp connection is made rather than at program start.
Obviously the socket is just an example, but I'm having a hard time thinking of when an encapsulated object with any sort of internal state shouldn't be created and initialised with new.