Circular references between two classes

≯℡__Kan透↙ 提交于 2019-12-05 09:04:36

You allocate your Server and Client instances on the stack, and they will be deleted when main() exits. You don't want std::shared_ptr deleting them as well. Thus, there are two solutions:

  1. Use unmanaged pointers within Client and Server, and manage their lifetimes externally.

  2. Use managed pointers everywhere, including main(). Do note that shared_ptr 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.

    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 weak_ptr to the client(s), but the clients would have a shared_ptr to the server.

class Client;
class Server;

class Client
{
public:
    void SetServer (const std::shared_ptr<const Server> &server);
private:
    std::shared_ptr<const Server> server;
};

void Client::SetServer (const std::shared_ptr<const Server> &server)
{
    this->server = server;
}

class Server
{
public:
    void SetClient (const std::weak_ptr<const Client> &client);
private:
    std::weak_ptr<const Client> client;
};

void Server::SetClient (const std::weak_ptr<const Client> &client)
{
    this->client = client;
}


int main()
{
  std::shared_ptr<Server> server(new Server);
  std::shared_ptr<Client> client(new Client);

  server->SetClient(client);
  client->SetServer(server);

  // do stuff

  return 0;
}

Your variables have automatic lifetime, and will be destroyed when they go out of scope.

Therefore, using any of the lifetime-managing smart pointers is wrong, because it will call delete a second time.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!