machinezone / IXWebSocket

websocket and http client and server library, with TLS support and very few dependencies
BSD 3-Clause "New" or "Revised" License
512 stars 167 forks source link

Question about weak_ptr in API #477

Open blitz-research opened 11 months ago

blitz-research commented 11 months ago

Hi,

Just curious to know why WebSocketServer::OnConnectionCallback takes a weak_ptr as its first argument and not a shared_ptr?

I don't often use weak_ptr so I'm not sure what I should infer from it's use here. I am just coverting it to a shared_ptr and capturing in the socket's own OnMessageCallback with no apparent ill effects, is this OK? eg:

    g_server->setOnConnectionCallback([](std::weak_ptr<ix::WebSocket> wsocket, std::shared_ptr<ix::ConnectionState>) { //
        log() << "### WebSocketServer new connection!";

        auto socket = wsocket.lock(); // convert to shared_ptr

        socket->setOnMessageCallback([socket](const ix::WebSocketMessagePtr& wsMsg) { //

            // blah blah blah...

            socket->send(result);
        });

And looking at the WebSocketServer code I can see it's originally a shared_ptr anyway so it seems a bit odd, although like I say I have no experience with weak_ptr (and not a lot with shared/unique ptrs either!)

Bye, Mark

bsergean commented 11 months ago

iirc it was to avoid potentially creating cycles (which you can with shared_ptr), but honestly I don't remember now. I think the shared_ptr version was triggering some compiler or rather runtime warnings about leaked memory.