I am writing an C++ websocket server library. In one of the examples I have provided I use two classes session_base
and session
. I do this so that I can have the tcp::socket
object in the session_base
parent class initialised (using a move constructor) before passing a reference to it to the ws::session<tcp::socket>
parent class which stores this reference for later use. The reason I have created ws:session as a template class is so i can use boost::asio::ssl::stream
s as well as tcp sockets.
Would it be valid to have the tcp::socket
object a member of the session
class, pass a reference to this uninitialised object to the ws::session
constructor (which doesn't use the tcp::socket
yet - only stores the reference) and then initialise the tcp::socket
object afterwards using the socket move constructor?
Current code:
using boost::asio::ip::tcp;
class session_base {
public:
session_base(tcp::socket socket) : socket_(std::move(socket)) { }
protected:
tcp::socket socket_;
};
using T = tcp::socket;
class session : public session_base, public ws::session<T> {
public:
session(tcp::socket socket) :
session_base(std::move(socket)), ws::session<T>(socket_)
{
std::cout << "session()\n";
}
~session() {
std::cout << "~session()\n";
}
private:
void on_open() override {
std::cout << "WebSocket connection open\n";
}
void on_msg(const ws::message &msg) override {
/* Do stuff with msg */
read();
}
void on_close() override {
std::cout << "WebSocket connection closed\n";
}
void on_error() override {
std::cout << "WebSocket connection error\n";
}
};
Proposed code:
The proposed code below works for me but i am wondering this is defined behaviour and recommended.
using boost::asio::ip::tcp;
using T = tcp::socket;
class session : public ws::session<T> {
public:
session(tcp::socket socket) :
ws::session<T>(socket_), socket_(std::move(socket))
{
std::cout << "session()\n";
}
~session() {
std::cout << "~session()\n";
}
private:
tcp::socket socket_;
void on_open() override {
std::cout << "WebSocket connection open\n";
}
void on_msg(const ws::message &msg) override {
/* Do stuff with msg */
read();
}
void on_close() override {
std::cout << "WebSocket connection closed\n";
}
void on_error() override {
std::cout << "WebSocket connection error\n";
}
};
Full source: https://github.com/alexyoung91/ws