Note that there are some explanatory texts on larger screens.

plurals
  1. POCircular references between two classes
    primarykey
    data
    text
    <p>I know this must be a n00b question, but I have to implement a mockup client-server sequential interaction application, and because the number of client-server calls varies, I cannot just iterate the steps in an external function, always fetching data from the client and then forwarding it to the server and vice-versa, so I need to make my <code>Server</code> and <code>Client</code> classes be aware of each other so that they can call their public methods between themselves. One approach would be to design both as Singletons, but I was hoping to do it in a simpler way, more precisely using a circular reference: the client stores a reference to the server and the server stores a reference to the client. I am aware that this might not be a good approach, and it could cause the call stack to explode <a href="https://stackoverflow.com/questions/1825964/c-c-maximum-stack-size-of-program">when it becomes too deep</a>, so any improvements to my design are welcomed.</p> <p>In order to achieve the described implementation, I thought that I could use <code>std::shared_ptr</code>, because <code>std::unique_ptr</code> won't work if I also want to prevent the two variables from main from getting clobbered when I call the two setters (right?). So, this is what I have (simplified code):</p> <pre><code>#include &lt;iostream&gt; #include &lt;memory&gt; class Server; class Client { public: void SetServer (const Server &amp;server); private: std::shared_ptr&lt;const Server&gt; server; }; void Client::SetServer (const Server &amp;server) { this-&gt;server = std::shared_ptr&lt;const Server&gt;(&amp;server); } class Server { public: void SetClient (const Client &amp;client); private: std::shared_ptr&lt;const Client&gt; client; }; void Server::SetClient (const Client &amp;client) { this-&gt;client = std::shared_ptr&lt;const Client&gt;(&amp;client); } int main () { Server server; Client client; server.SetClient(client); client.SetServer(server); //Here I ask the client to start interacting with the server. //The process will terminate once the client //exhausts all the data it needs to send to the server for processing return 0; } </code></pre> <p>Unfortunately, my code seems to try to call the Client and Server (implicit) destructors multiple times, or some similar nasty thing, and I'm certain that this is caused by my poor understanding of how <code>std::shared_ptr</code> is supposed to work. Please advise.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    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