Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You allocate your Server and Client instances on the stack, and they will be deleted when <code>main()</code> exits. You don't want <code>std::shared_ptr</code> deleting them as well. Thus, there are two solutions:</p> <ol> <li><p>Use unmanaged pointers within Client and Server, and manage their lifetimes externally.</p></li> <li><p>Use managed pointers everywhere, including <code>main()</code>. Do note that <code>shared_ptr</code> implies ownership. In the current design, a Server owns the client, but also a Client owns the server. That's a circular reference: by default, they'll never be freed, unless you reset one of those pointers while you still can.</p> <p>As an example, you can decide that the clients keep the server alive, thus last vanishing client will bring down the server if there are no other shared_ptrs pointing at it. The server would have a <code>weak_ptr</code> to the client(s), but the clients would have a <code>shared_ptr</code> to the server.</p></li> </ol> <pre><code>class Client; class Server; class Client { public: void SetServer (const std::shared_ptr&lt;const Server&gt; &amp;server); private: std::shared_ptr&lt;const Server&gt; server; }; void Client::SetServer (const std::shared_ptr&lt;const Server&gt; &amp;server) { this-&gt;server = server; } class Server { public: void SetClient (const std::weak_ptr&lt;const Client&gt; &amp;client); private: std::weak_ptr&lt;const Client&gt; client; }; void Server::SetClient (const std::weak_ptr&lt;const Client&gt; &amp;client) { this-&gt;client = client; } int main() { std::shared_ptr&lt;Server&gt; server(new Server); std::shared_ptr&lt;Client&gt; client(new Client); server-&gt;SetClient(client); client-&gt;SetServer(server); // do stuff return 0; } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload