2

I'm trying to create TCP client class in C++. I wrote my class like below and on const I want to enable receive_once and send_data only.
send_data and receive_once has some exception to disconnect directly(something like sigpipe, negative return from receive...). So send_data, receive_once have to call disconnect in some cases.

class TcpClient {
public:
    TcpClient();
    void connect_server(ip, port);
    void disconnect();
    void send_data(payload) const {
        if (sigpipe) disconnect();
    }
    void receive_once(payload) const {
        if (len == -1) disconnect();
    }
}

But I want to enable send_data, receive_once only on const. I want to disable connect_server, disconnect directly on const but, it has to disconnected on some cases like sigpipe. Is there any trick to do this?

int main() {
    const TcpClient tcp_client;
    tcp_client.connect_server(ip, port); // DISABLE
    tcp_client.disconnect(); //DISABLE
    tcp_client.send_data(payload); //ENABLE
    tcp_client.receive_once(payload); //ENABLE
}
  • 1
    If you want them to be `const`, you can't get around this. Better redesign and report the error to the caller somehow, then they can call disconnect or get rid of the client object. – Zuodian Hu Apr 05 '20 at 04:08
  • But I want to disconnect automatically on error. Isn't it weird make caller to disconnect manually? –  Apr 05 '20 at 04:14
  • 1
    @Penguin: "*I want to enable send_data, receive_once only on const*" What do you mean by "only on `const`"? "*Isn't it weird make caller to disconnect manually?*" It's a lot more weird for a user to invoke a `const` operation and to have it do a non-`const` thing on that object. If disconnecting isn't `const`, then why should a `const` function be able to do it? – Nicol Bolas Apr 05 '20 at 04:24
  • 3
    If `disconnect` is not `const`, those functions cannot be `const` and also call `disconnect`. Can't you do the disconnection in the destructor or some sort of `reconnect` function? Then the user still doesn't have to call `disconnect` manually – Zuodian Hu Apr 05 '20 at 04:25
  • 1
    See https://stackoverflow.com/questions/105014/does-the-mutable-keyword-have-any-purpose-other-than-allowing-the-variable-to. You can also have const and non-const overload of each member function – Mike Lui Apr 05 '20 at 05:34

0 Answers0