From d82fb914363a32398bd9adae181e808f3c8e603e Mon Sep 17 00:00:00 2001 From: David Baird Date: Fri, 27 Sep 2013 14:14:43 -0600 Subject: [PATCH] Clean up memory in examples. --- README.md | 2 ++ example-client-cpp11.cpp | 9 ++++++--- example-client.cpp | 1 + 3 files changed, 9 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index d3d51f2..dc7b1b5 100644 --- a/README.md +++ b/README.md @@ -76,6 +76,8 @@ main() // ...do more stuff... } ... + delete ws; // alternatively, use unique_ptr<> if you have C++11 + return 0; } ``` diff --git a/example-client-cpp11.cpp b/example-client-cpp11.cpp index 6232957..39917ec 100644 --- a/example-client-cpp11.cpp +++ b/example-client-cpp11.cpp @@ -5,20 +5,23 @@ #include #include #include +#include int main() { using easywsclient::WebSocket; - WebSocket::pointer ws = WebSocket::from_url("ws://localhost:8126/foo"); + std::unique_ptr ws(WebSocket::from_url("ws://localhost:8126/foo")); assert(ws); ws->send("goodbye"); ws->send("hello"); while (ws->getReadyState() != WebSocket::CLOSED) { + WebSocket::pointer wsp = &*ws; // <-- because a unique_ptr cannot be copied into a lambda ws->poll(); - ws->dispatch([ws](const std::string & message) { + ws->dispatch([wsp](const std::string & message) { printf(">>> %s\n", message.c_str()); - if (message == "world") { ws->close(); } + if (message == "world") { wsp->close(); } }); } + // N.B. - unique_ptr will free the WebSocket instance upon return: return 0; } diff --git a/example-client.cpp b/example-client.cpp index a10a0e8..5fe1884 100644 --- a/example-client.cpp +++ b/example-client.cpp @@ -23,5 +23,6 @@ int main() ws->poll(); ws->dispatch(handle_message); } + delete ws; return 0; }