The RWSocketPortal class uses the "resource acquisition is initialization" technique to avoid the problems described in the previous section. Since RWSocketPortal uses the interface-implementation pattern described in Chapter 11, copy and assignment semantics do the appropriate thing.
You can get a copy of the socket inside a socket portal. All of the functionality of sockets is then made available to you. For example, suppose code that uses socket portals needs to print out a line describing both ends of the connection. Here is one way to do this:
RWSocket sock = sockPortal.socket(); //1 cout << sock.id(); //2
//1 | Make a copy of the socket used by the RWSocketPortal sockPortal. The socket returned refers to the same communications channel as the socket portal. Since the socket portal automatically closes this channel once all RWSocketPortal references to the channel are gone, the RWSocket should only be used while the RWSocketPortal is in scope. |
//2 | Print out an identifier giving both ends of the connection. |
We could also have accomplished this in one line, by using a temporary socket:
cout << sockPortal.socket().id();
By using a temporary variable, the lifetime of the RWSocket is guaranteed to be as short as the socket portal's lifetime.
Since the socket member function returns a new socket, and not a reference to the actual socket used by the RWSocketPortal you can't reassign the portal's socket like this:
socketPortal.socket() = anotherSocket; // Nope!
©Copyright 2000, Rogue Wave Software, Inc.
Contact Rogue Wave about documentation or support issues.