How to release pointer from boost::shared_ptr?

后端 未结 14 1600
刺人心
刺人心 2020-11-30 06:42

Can boost::shared_ptr release the stored pointer without deleting it?

I can see no release function exists in the documentation, also in the FAQ is explained why it

14条回答
  •  时光取名叫无心
    2020-11-30 06:49

    I am using Poco::HTTPRequestHandlerFactory which expects to return a raw HTTPRequestHandler*, the Poco framework deletes the handler once the request finishes.

    Also using DI Sauce project to create the controllers, however the Injector returns shared_ptr which I cannot return directly, and returning handler.get() is no good either since the as soon as this function returns the shared_ptr goes out of scope and deletes then handler before its executed, so here is a reasonable (I think) reason to have a .release() method. I ended up creating a HTTPRequestHandlerWrapper class as follows :-

    class HTTPRequestHandlerWrapper : public HTTPRequestHandler {
    private:
        sauce::shared_ptr _handler;
    
    public:
        HTTPRequestHandlerWrapper(sauce::shared_ptr handler) {
            _handler = handler;
        }
    
        virtual void handleRequest(HTTPServerRequest& request, HTTPServerResponse& response) {
            return _handler->handleRequest(request, response);
        }
    };
    

    and then the factory would

    HTTPRequestHandler* HttpHandlerFactory::createRequestHandler(const HTTPServerRequest& request) {
        URI uri = URI(request.getURI());
        auto path = uri.getPath();
        auto method = request.getMethod();
    
        sauce::shared_ptr handler = _injector->get(method + ":" + path);
    
        return new HTTPRequestHandlerWrapper(handler);
    }
    

    which satisfied both Sauce and Poco and works nicely.

提交回复
热议问题