Using Socket Portals
If you make a copy of a socket inside of an RWSocketPortal, all of the functionality of the socket is available. In addition, you avoid the resource leaks described in Closing Sockets and Avoiding Resource Leaks because the RWSocketPortal class uses the “resource acquisition is initialization” technique. RWSocketPortal also uses the interface-implementation idiom described in Understanding the Portal and Implementation Classes.
The following code uses socket portals and prints a description of both ends of the connection.
 
RWSocket sock = sockPortal.getSocket(); //1
cout << sock.id(); //2
//1 Makes a copy of the socket used by the RWSocketPortal sockPortal. The socket returned refers to the same communications channel as the socket portal. Because 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 Prints the identifier.
The following code uses a temporary socket to print the description:
 
cout << sockPortal.getSocket().id();
By using a temporary variable, the lifetime of the RWSocket is guaranteed to be as short as the RWSocketPortal’s lifetime.
The getSocket() member function returns a new RWSocket and not a reference to the actual RWSocket used by the RWSocketPortal, so you cannot reassign the RWSocketPortal’s RWSocket. The following code is incorrect:
 
socketPortal.getSocket() = anotherSocket; // No!