Question

I working currenly on server using Poco Net & Reactor Pattern. I watned to do class CSConnection unique_ptr because class objects are referenced to worker thread pool.

Constructor :

    CSConnection::CSConnection(StreamSocket& socket, SocketReactor& reactor) : _socket(socket), _reactor(reactor)
    {
std::unique_ptr<CSConnection> autoptr(this);
        app.logger().information("Connection : " + _socket.peerAddress().toString());
        _reactor.addEventHandler(_socket, NObserver<CSConnection, ReadableNotification>(*this, &CSConnection::onReadable));
        _reactor.addEventHandler(_socket, NObserver<CSConnection, ShutdownNotification>(*this, &CSConnection::onShutdown));
        _reactor.addEventHandler(_socket, NObserver<CSConnection, ErrorNotification>(*this, &CSConnection::onError));
        _socket.setBlocking(false);
        sendSync();
    }

Destructor :

CSConnection::~CSConnection()
{
    app.logger().information("Disconnect : " + _socket.peerAddress().toString());
    _reactor.removeEventHandler(_socket, NObserver<CSConnection, ReadableNotification>(*this, &CSConnection::onReadable));
    _reactor.removeEventHandler(_socket, NObserver<CSConnection, ShutdownNotification>(*this, &CSConnection::onShutdown));
    _reactor.removeEventHandler(_socket, NObserver<CSConnection, ErrorNotification>(*this, &CSConnection::onError));
    if(player)
    {
        player->relase();
        if(player->hasActiveCharacter())
        {
            player->getActiveCharacter()->leaveGameWorld();
            player->nullActive();
        }
    }
}

And after that application free that class instantly (can be observed by "Disconnect" in server log).

What is there wrong ? Thanks.

Était-ce utile?

La solution

std::unique_ptr<CSConnection> autoptr(this);

After going out of the constructor it tries to delete this and calling the destructor. it's undefined behavior to use the deleted object after constructing it in this case.

Suicide (delete this) is rare and has special usage, for example in reference counted objects.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top