Skip to content

Custom user data per-connection, using Empty Base Optimization for zero overhead

A proof-of-concept sketch. Not happy with the names used, and maybe the data should be attached to Session instead of Connection

As it uses Empty Base Optimization, should have zero impact on code that does not need the feature. And existing code should compile without modification.

Example use:

class UserSessionData
{
public:
	UserSessionData()
	  : stuff{ "Hello" }, timer{0}
	{ std::cout << "UserSessionData : Constructed!" << std::endl; }
	UserSessionData(UserSessionData&) = delete;  // Avoid accidental copying, we only want refs
	~UserSessionData() { std::cout << "UserSessionData : Destructed!" << std::endl; }

	std::string stuff;
	int timer;  // Notice this doesn't affect the member in Connection with the same name
};

...

using HttpServer = SimpleWeb::Server<SimpleWeb::HTTP, UserSessionData>;

...

server.default_resource["GET"] = [](std::shared_ptr<HttpServer::Response> response, std::shared_ptr<HttpServer::Request> request) {
	auto& data = response->get_user_data();
	data.stuff += "!";
	std::cout << "data = " << data.stuff << std::endl;

	SimpleWeb::CaseInsensitiveMultimap header;
	header.emplace("Content-Type", "text/plain");
	response->write(data.stuff, header);
};

Merge request reports