【发布时间】:2012-06-20 19:48:55
【问题描述】:
我知道这一定是一个n00b问题,但我必须实现一个模型客户端-服务器顺序交互应用程序,并且由于客户端-服务器调用的数量不同,我不能只在外部函数中迭代步骤,总是获取来自客户端的数据,然后将其转发到服务器,反之亦然,所以我需要让我的 Server 和 Client 类相互了解,以便它们可以在它们之间调用它们的公共方法。一种方法是将两者都设计为单例,但我希望以更简单的方式来实现,更准确地说是使用循环引用:客户端存储对服务器的引用,服务器存储对客户端的引用。我知道这可能不是一个好方法,它可能会导致调用堆栈爆炸when it becomes too deep,因此欢迎对我的设计进行任何改进。
为了实现所描述的实现,我认为我可以使用std::shared_ptr,因为如果我还想防止 main 中的两个变量在调用两个 setter 时被破坏,std::unique_ptr 将不起作用(对?)。所以,这就是我所拥有的(简化代码):
#include <iostream>
#include <memory>
class Server;
class Client
{
public:
void SetServer (const Server &server);
private:
std::shared_ptr<const Server> server;
};
void Client::SetServer (const Server &server)
{
this->server = std::shared_ptr<const Server>(&server);
}
class Server
{
public:
void SetClient (const Client &client);
private:
std::shared_ptr<const Client> client;
};
void Server::SetClient (const Client &client)
{
this->client = std::shared_ptr<const Client>(&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;
}
不幸的是,我的代码似乎试图多次调用客户端和服务器(隐式)析构函数,或者一些类似的讨厌的事情,我确信这是由于我对 std::shared_ptr 的理解不足造成的工作。请指教。
【问题讨论】:
-
+1 表示自包含的完整示例程序。 sscce.org.
-
您将服务器和客户端参数作为引用传递给 SetXxxx。这不是人们通常会这样做的方式。我认为将这些作为指针传递是惯用的。理想情况下,作为智能指针,而不是裸指针。
-
@KubaOber 我会努力解决的。感谢您指出问题。
标签: c++ pointers client-server pass-by-reference circular-reference