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
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!