关于类不生成默认构造函数的问题
项目中用到http server,选用了cpp-httplib,
我们创建类,以组合的形式对httplib::Server进行了封装:
class HttpServer { public: /* HttpServer(const HttpServer& server){ m_httplibServer = server.m_httplibServer; // 错误:使用了被删除的函数‘httplib::Server& httplib::Server::operator=(const httplib::Server&)’ m_serverHost = server.m_serverHost; m_port = m_serverHost.m_port; } */ HttpServer(const std::string &host = "127.0.0.1", int32_t port = 8080) : m_serverHost(host), m_port(port) { } private: httplib::Server m_httplibServer; std::string m_serverHost; int32_t m_port; };
HttpServer又作为上层Controller类的对象:
class Controller { public: Controller(); HttpServer &GetHttpServer() { return m_httpServer; } private: HttpServer m_httpServer; };
在main函数里对其调用:
HttpServer httpServer = m_controller.GetHttpServer();
httpServer.RegisterHttpInterfaces(intf1400.Get1400Interfaces());
一直报错:
错误:使用了被删除的函数‘HttpServer::HttpServer(const HttpServer&)’ HttpServer httpServer = m_controller.GetHttpServer();
分析原因:从报错看,好像是HttpServer类没有拷贝构造函数,但是默认情况下应该自己生成的,随即把
HttpServer httpServer = m_controller.GetHttpServer();
里对引用返回值的接收类型改为引用:
HttpServer &httpServer = m_controller.GetHttpServer();
则可以编译通过,应该是因为引用接收不涉及拷贝构造函数的调用。
那么为什么编译器不为HttpServer类生成默认拷贝构造函数呢?不生成,那我自己写了一个试试:
class HttpServer { public: HttpServer(const HttpServer& server){ m_httplibServer = server.m_httplibServer; m_serverHost = server.m_serverHost; m_port = m_serverHost.m_port; } HttpServer(const std::string &host = "127.0.0.1", int32_t port = 8080) : m_serverHost(host), m_port(port) { } private: httplib::Server m_httplibServer; std::string m_serverHost; int32_t m_port; };
编译提示错误:
错误:使用了被删除的函数‘httplib::Server& httplib::Server::operator=(const httplib::Server&)’
猜想可能是cpp-httplib没有为httplib::Server实现‘=’操作符的重载,也没实现拷贝构造函数,先记录一下问题,后面有空再验证一下。