Răsfoiți Sursa

optimize #398: std::make_shared

ithewei 2 ani în urmă
părinte
comite
0cbf8eb8cf

+ 1 - 1
evpp/EventLoop.h

@@ -176,7 +176,7 @@ public:
     void postEvent(EventCallback cb) {
         if (loop_ == NULL) return;
 
-        EventPtr ev(new Event(cb));
+        EventPtr ev = std::make_shared<Event>(cb);
         hevent_set_userdata(&ev->event, this);
         ev->event.cb = onCustomEvent;
 

+ 1 - 1
evpp/EventLoopThread.h

@@ -46,7 +46,7 @@ public:
         if (status() >= kStarting && status() < kStopped) return;
         setStatus(kStarting);
 
-        thread_.reset(new std::thread(&EventLoopThread::loop_thread, this, pre, post));
+        thread_ = std::make_shared<std::thread>(&EventLoopThread::loop_thread, this, pre, post);
 
         if (wait_thread_started) {
             while (loop_->status() < kRunning) {

+ 7 - 7
evpp/EventLoopThreadPool.h

@@ -29,16 +29,16 @@ public:
     }
 
     EventLoopPtr nextLoop(load_balance_e lb = LB_RoundRobin) {
-        int numLoops = loop_threads_.size();
+        size_t numLoops = loop_threads_.size();
         if (numLoops == 0) return NULL;
-        int idx = 0;
+        size_t idx = 0;
         if (lb == LB_RoundRobin) {
             if (++next_loop_idx_ >= numLoops) next_loop_idx_ = 0;
             idx = next_loop_idx_ % numLoops;
         } else if (lb == LB_Random) {
             idx = hv_rand(0, numLoops - 1);
         } else if (lb == LB_LeastConnections) {
-            for (int i = 1; i < numLoops; ++i) {
+            for (size_t i = 1; i < numLoops; ++i) {
                 if (loop_threads_[i]->loop()->connectionNum < loop_threads_[idx]->loop()->connectionNum) {
                     idx = i;
                 }
@@ -50,7 +50,7 @@ public:
     }
 
     EventLoopPtr loop(int idx = -1) {
-        if (idx >= 0 && idx < loop_threads_.size()) {
+        if (idx >= 0 && idx < (int)loop_threads_.size()) {
             return loop_threads_[idx]->loop();
         }
         return nextLoop();
@@ -71,12 +71,12 @@ public:
         if (status() >= kStarting && status() < kStopped) return;
         setStatus(kStarting);
 
-        std::shared_ptr<std::atomic<int>> started_cnt(new std::atomic<int>(0));
-        std::shared_ptr<std::atomic<int>> exited_cnt(new std::atomic<int>(0));
+        auto started_cnt = std::make_shared<std::atomic<int>>(0);
+        auto exited_cnt  = std::make_shared<std::atomic<int>>(0);
 
         loop_threads_.clear();
         for (int i = 0; i < thread_num_; ++i) {
-            EventLoopThreadPtr loop_thread(new EventLoopThread);
+            auto loop_thread = std::make_shared<EventLoopThread>();
             const EventLoopPtr& loop = loop_thread->loop();
             loop_thread->start(false,
                 [this, started_cnt, pre, &loop]() {

+ 1 - 1
evpp/EventLoop_test.cpp

@@ -20,7 +20,7 @@ int main(int argc, char* argv[]) {
 
     printf("main tid=%ld\n", hv_gettid());
 
-    EventLoopPtr loop(new EventLoop);
+    auto loop = std::make_shared<EventLoop>();
 
     // runEvery 1s
     loop->setInterval(1000, std::bind(onTimer, std::placeholders::_1, 100));

+ 1 - 1
evpp/TcpClient.h

@@ -59,7 +59,7 @@ public:
         hio_t* io = hio_get(loop_->loop(), connfd);
         assert(io != NULL);
         hio_set_peeraddr(io, remote_addr, SOCKADDR_LEN(remote_addr));
-        channel.reset(new TSocketChannel(io));
+        channel = std::make_shared<TSocketChannel>(io);
         return connfd;
     }
 

+ 1 - 1
evpp/TcpClientEventLoop_test.cpp

@@ -74,7 +74,7 @@ public:
 typedef std::shared_ptr<MyTcpClient> MyTcpClientPtr;
 
 int TestMultiClientsRunInOneEventLoop(int port, int nclients) {
-    EventLoopThreadPtr loop_thread(new EventLoopThread);
+    auto loop_thread = std::make_shared<EventLoopThread>();
     loop_thread->start();
 
     std::map<int, MyTcpClientPtr> clients;

+ 1 - 1
evpp/TcpServer.h

@@ -146,7 +146,7 @@ public:
     // channel
     const TSocketChannelPtr& addChannel(hio_t* io) {
         uint32_t id = hio_id(io);
-        auto channel = TSocketChannelPtr(new TSocketChannel(io));
+        auto channel = std::make_shared<TSocketChannel>(io);
         std::lock_guard<std::mutex> locker(mutex_);
         channels[id] = channel;
         return channels[id];

+ 1 - 1
evpp/UdpClient.h

@@ -38,7 +38,7 @@ public:
         if (io == NULL) return -1;
         this->remote_host = remote_host;
         this->remote_port = remote_port;
-        channel.reset(new TSocketChannel(io));
+        channel = std::make_shared<TSocketChannel>(io);
         int sockfd = channel->fd();
         if (hv_strendswith(remote_host, ".255")) {
             udp_broadcast(sockfd, 1);

+ 1 - 1
evpp/UdpServer.h

@@ -37,7 +37,7 @@ public:
         if (io == NULL) return -1;
         this->host = host;
         this->port = port;
-        channel.reset(new TSocketChannel(io));
+        channel = std::make_shared<TSocketChannel>(io);
         return channel->fd();
     }
     // closesocket thread-safe

+ 2 - 2
examples/http_client_test.cpp

@@ -15,7 +15,7 @@ using namespace hv;
 
 static void test_http_async_client(HttpClient* cli, int* resp_cnt) {
     printf("test_http_async_client request thread tid=%ld\n", hv_gettid());
-    HttpRequestPtr req(new HttpRequest);
+    auto req = std::make_shared<HttpRequest>();
     req->method = HTTP_POST;
     req->url = "http://127.0.0.1:8080/echo";
     req->headers["Connection"] = "keep-alive";
@@ -101,7 +101,7 @@ static void test_requests() {
 
     // async
     /*
-    // Request req(new HttpRequest);
+    // auto req = std::make_shared<HttpRequest>();
     req->url = "http://127.0.0.1:8080/echo";
     req->method = HTTP_POST;
     req->body = "This is an async request.";

+ 1 - 1
examples/httpd/router.cpp

@@ -80,7 +80,7 @@ void Router::Register(hv::HttpService& router) {
     // curl -v http://ip:port/www.*
     // curl -v http://ip:port/www.example.com
     router.GET("/www.*", [](const HttpRequestPtr& req, const HttpResponseWriterPtr& writer) {
-        HttpRequestPtr req2(new HttpRequest);
+        auto req2 = std::make_shared<HttpRequest>();
         req2->url = req->path.substr(1);
         requests::async(req2, [writer](const HttpResponsePtr& resp2){
             writer->Begin();

+ 5 - 5
examples/protorpc/protorpc_client.cpp

@@ -114,7 +114,7 @@ public:
                 return;
             }
             // Response::ParseFromArray
-            protorpc::ResponsePtr res(new protorpc::Response);
+            auto res = std::make_shared<protorpc::Response>();
             if (!res->ParseFromArray(msg.body, msg.head.length)) {
                 return;
             }
@@ -145,9 +145,9 @@ public:
         static std::atomic<uint64_t> s_id = ATOMIC_VAR_INIT(0);
         req->set_id(++s_id);
         req->id();
-        auto ctx = new protorpc::ProtoRpcContext;
+        auto ctx = std::make_shared<protorpc::ProtoRpcContext>();
         ctx->req = req;
-        calls[req->id()] = protorpc::ContextPtr(ctx);
+        calls[req->id()] = ctx;
         // Request::SerializeToArray + protorpc_pack
         protorpc_message msg;
         protorpc_message_init(&msg);
@@ -177,7 +177,7 @@ public:
     }
 
     int calc(const char* method, int num1, int num2, int& out) {
-        protorpc::RequestPtr req(new protorpc::Request);
+        auto req = std::make_shared<protorpc::Request>();
         // method
         req->set_method(method);
         // params
@@ -199,7 +199,7 @@ public:
     }
 
     int login(const protorpc::LoginParam& param, protorpc::LoginResult* result) {
-        protorpc::RequestPtr req(new protorpc::Request);
+        auto req = std::make_shared<protorpc::Request>();
         // method
         req->set_method("login");
         // params

+ 2 - 2
examples/websocket_client_test.cpp

@@ -42,7 +42,7 @@ public:
         setReconnect(&reconn);
 
         /*
-        HttpRequestPtr req = std::make_shared<HttpRequest>();
+        auto req = std::make_shared<HttpRequest>();
         req->method = HTTP_POST;
         req->headers["Origin"] = "http://example.com";
         req->json["app_id"] = "123456";
@@ -59,7 +59,7 @@ public:
 typedef std::shared_ptr<MyWebSocketClient> MyWebSocketClientPtr;
 
 int TestMultiClientsRunInOneEventLoop(const char* url, int nclients) {
-    EventLoopThreadPtr loop_thread(new EventLoopThread);
+    auto loop_thread = std::make_shared<EventLoopThread>();
     loop_thread->start();
 
     std::map<int, MyWebSocketClientPtr> clients;

+ 2 - 2
examples/wrk.cpp

@@ -51,7 +51,7 @@ typedef struct connection_s {
 
     connection_s()
         : parser(HttpParser::New(HTTP_CLIENT, HTTP_V1))
-        , response(new HttpResponse)
+        , response(std::make_shared<HttpResponse>())
         , request_cnt(0)
         , response_cnt(0)
         , ok_cnt(0)
@@ -211,7 +211,7 @@ int main(int argc, char** argv) {
     print_cmd();
 
     // ParseUrl
-    request.reset(new HttpRequest);
+    request = std::make_shared<HttpRequest>();
     request->url = url;
     request->ParseUrl();
     https = request->scheme == "https";

+ 5 - 6
http/client/AsyncHttpClient.cpp

@@ -166,18 +166,17 @@ int AsyncHttpClient::doTask(const HttpClientTaskPtr& task) {
 int AsyncHttpClient::sendRequest(const SocketChannelPtr& channel) {
     HttpClientContext* ctx = (HttpClientContext*)channel->context();
     assert(ctx != NULL && ctx->task != NULL);
+    if (ctx->resp == NULL) {
+        ctx->resp = std::make_shared<HttpResponse>();
+    }
     HttpRequest* req = ctx->task->req.get();
     HttpResponse* resp = ctx->resp.get();
+    assert(req != NULL && resp != NULL);
+    if (req->http_cb) resp->http_cb = std::move(req->http_cb);
 
     if (ctx->parser == NULL) {
         ctx->parser.reset(HttpParser::New(HTTP_CLIENT, (http_version)req->http_major));
     }
-    if (resp == NULL) {
-        resp = new HttpResponse;
-        ctx->resp.reset(resp);
-    }
-    if (req->http_cb) resp->http_cb = std::move(req->http_cb);
-
     ctx->parser->InitResponse(resp);
     ctx->parser->SubmitRequest(req);
 

+ 2 - 2
http/client/AsyncHttpClient.h

@@ -115,7 +115,7 @@ public:
 
     // thread-safe
     int send(const HttpRequestPtr& req, HttpResponseCallback resp_cb) {
-        HttpClientTaskPtr task(new HttpClientTask);
+        auto task = std::make_shared<HttpClientTask>();
         task->req = req;
         task->cb = std::move(resp_cb);
         task->start_time = hloop_now_hrtime(EventLoopThread::hloop());
@@ -148,7 +148,7 @@ protected:
     }
 
     const SocketChannelPtr& addChannel(hio_t* io) {
-        SocketChannelPtr channel(new SocketChannel(io));
+        auto channel = std::make_shared<SocketChannel>(io);
         channel->newContext<HttpClientContext>();
         int fd = channel->fd();
         channels[fd] = channel;

+ 1 - 1
http/client/HttpClient.cpp

@@ -656,7 +656,7 @@ static int http_client_exec_async(http_client_t* cli, HttpRequestPtr req, HttpRe
     if (cli->async_client_ == NULL) {
         cli->mutex_.lock();
         if (cli->async_client_ == NULL) {
-            cli->async_client_.reset(new hv::AsyncHttpClient);
+            cli->async_client_ = std::make_shared<hv::AsyncHttpClient>();
         }
         cli->mutex_.unlock();
     }

+ 3 - 3
http/client/WebSocketClient.cpp

@@ -39,7 +39,7 @@ int WebSocketClient::open(const char* _url, const http_headers& headers) {
     }
     hlogi("%s", url.c_str());
     if (!http_req_) {
-        http_req_.reset(new HttpRequest);
+        http_req_ = std::make_shared<HttpRequest>();
     }
     // ws => http
     http_req_->url = "http" + url.substr(2, -1);
@@ -88,7 +88,7 @@ int WebSocketClient::open(const char* _url, const http_headers& headers) {
             state = WS_UPGRADING;
             // prepare HttpParser
             http_parser_.reset(HttpParser::New(HTTP_CLIENT, HTTP_V1));
-            http_resp_.reset(new HttpResponse);
+            http_resp_ = std::make_shared<HttpResponse>();
             http_parser_->InitResponse(http_resp_.get());
         } else {
             state = WS_CLOSED;
@@ -137,7 +137,7 @@ int WebSocketClient::open(const char* _url, const http_headers& headers) {
                     channel->close();
                     return;
                 }
-                ws_parser_.reset(new WebSocketParser);
+                ws_parser_ = std::make_shared<WebSocketParser>();
                 // websocket_onmessage
                 ws_parser_->onMessage = [this, &channel](int opcode, const std::string& msg) {
                     channel->opcode = (enum ws_opcode)opcode;

+ 1 - 1
http/client/axios.h

@@ -65,7 +65,7 @@ using requests::ResponseCallback;
 namespace axios {
 
 HV_INLINE Request newRequestFromJson(const json& jreq) {
-    Request req(new HttpRequest);
+    auto req = std::make_shared<HttpRequest>();
     // url
     if (jreq.contains("url")) {
         req->url = jreq["url"];

+ 7 - 7
http/client/requests.h

@@ -40,13 +40,13 @@ typedef HttpResponsePtr         Response;
 typedef HttpResponseCallback    ResponseCallback;
 
 HV_INLINE Response request(Request req) {
-    Response resp(new HttpResponse);
+    auto resp = std::make_shared<HttpResponse>();
     int ret = http_client_send(req.get(), resp.get());
     return ret ? NULL : resp;
 }
 
 HV_INLINE Response request(http_method method, const char* url, const http_body& body = NoBody, const http_headers& headers = DefaultHeaders) {
-    Request req(new HttpRequest);
+    auto req = std::make_shared<HttpRequest>();
     req->method = method;
     req->url = url;
     if (&body != &NoBody) {
@@ -89,7 +89,7 @@ HV_INLINE int async(Request req, ResponseCallback resp_cb) {
 
 // Sample codes for uploading and downloading files
 HV_INLINE Response uploadFile(const char* url, const char* filepath, http_method method = HTTP_POST, const http_headers& headers = DefaultHeaders) {
-    Request req(new HttpRequest);
+    auto req = std::make_shared<HttpRequest>();
     req->method = method;
     req->url = url;
     req->timeout = 600; // 10min
@@ -102,7 +102,7 @@ HV_INLINE Response uploadFile(const char* url, const char* filepath, http_method
 
 #ifndef WITHOUT_HTTP_CONTENT
 HV_INLINE Response uploadFormFile(const char* url, const char* name, const char* filepath, std::map<std::string, std::string>& params = hv::empty_map, http_method method = HTTP_POST, const http_headers& headers = DefaultHeaders) {
-    Request req(new HttpRequest);
+    auto req = std::make_shared<HttpRequest>();
     req->method = method;
     req->url = url;
     req->timeout = 600; // 10min
@@ -128,7 +128,7 @@ HV_INLINE Response uploadLargeFile(const char* url, const char* filepath, upload
     }
 
     hv::HttpClient cli;
-    Request req(new HttpRequest);
+    auto req = std::make_shared<HttpRequest>();
     req->method = method;
     req->url = url;
     req->timeout = 3600; // 1h
@@ -172,7 +172,7 @@ HV_INLINE Response uploadLargeFile(const char* url, const char* filepath, upload
     }
 
     // recv response
-    Response resp(new HttpResponse);
+    auto resp = std::make_shared<HttpResponse>();
     ret = cli.recvResponse(resp.get());
     if (ret != 0) {
         return NULL;
@@ -192,7 +192,7 @@ HV_INLINE size_t downloadFile(const char* url, const char* filepath, download_pr
         return 0;
     }
     // download
-    Request req(new HttpRequest);
+    auto req = std::make_shared<HttpRequest>();
     req->method = HTTP_GET;
     req->url = url;
     req->timeout = 3600; // 1h

+ 1 - 1
http/server/FileCache.cpp

@@ -56,7 +56,7 @@ file_cache_ptr FileCache::Open(const char* filepath, OpenParam* param) {
             if (S_ISREG(st.st_mode) ||
                 (S_ISDIR(st.st_mode) &&
                  filepath[strlen(filepath)-1] == '/')) {
-                fc.reset(new file_cache_t);
+                fc = std::make_shared<file_cache_t>();
                 fc->filepath = filepath;
                 fc->st = st;
                 time(&fc->open_time);

+ 5 - 5
http/server/HttpHandler.cpp

@@ -55,8 +55,8 @@ bool HttpHandler::Init(int http_version) {
     if (parser == NULL) {
         return false;
     }
-    req.reset(new HttpRequest);
-    resp.reset(new HttpResponse);
+    req  = std::make_shared<HttpRequest>();
+    resp = std::make_shared<HttpResponse>();
     if(http_version == 1) {
         protocol = HTTP_V1;
     } else if (http_version == 2) {
@@ -68,7 +68,7 @@ bool HttpHandler::Init(int http_version) {
         hloop_t* loop = hevent_loop(io);
         pid = hloop_pid(loop);
         tid = hloop_tid(loop);
-        writer.reset(new hv::HttpResponseWriter(io, resp));
+        writer = std::make_shared<HttpResponseWriter>(io, resp);
         writer->status = hv::SocketChannel::CONNECTED;
     } else {
         pid = hv_getpid();
@@ -157,8 +157,8 @@ bool HttpHandler::SwitchWebSocket() {
     if(!io) return false;
 
     protocol = WEBSOCKET;
-    ws_parser.reset(new WebSocketParser);
-    ws_channel.reset(new hv::WebSocketChannel(io, WS_SERVER));
+    ws_parser  = std::make_shared<WebSocketParser>();
+    ws_channel = std::make_shared<WebSocketChannel>(io, WS_SERVER);
     ws_parser->onMessage = [this](int opcode, const std::string& msg){
         ws_channel->opcode = (enum ws_opcode)opcode;
         switch(opcode) {

+ 2 - 2
http/server/HttpServer.cpp

@@ -96,7 +96,7 @@ static void loop_thread(void* userdata) {
     http_server_t* server = (http_server_t*)userdata;
     HttpService* service = server->service;
 
-    EventLoopPtr loop(new EventLoop);
+    auto loop = std::make_shared<EventLoop>();
     hloop_t* hloop = loop->loop();
     // http
     if (server->listenfd[0] >= 0) {
@@ -196,7 +196,7 @@ int http_server_run(http_server_t* server, int wait) {
     HttpServerPrivdata* privdata = new HttpServerPrivdata;
     server->privdata = privdata;
     if (server->service == NULL) {
-        privdata->service.reset(new HttpService);
+        privdata->service = std::make_shared<HttpService>();
         server->service = privdata->service.get();
     }