Is it possible to defer member initialization to the constructor body?

后端 未结 8 611
一生所求
一生所求 2021-01-13 14:25

I have a class with an object as a member which doesn\'t have a default constructor. I\'d like to initialize this member in the constructor, but it seems that in C++ I can\'

8条回答
  •  南笙
    南笙 (楼主)
    2021-01-13 14:43

    Another option in this case is to work around the issue by creating a static function to build ep:

    #include 
    #include 
    
    using boost::asio::ip::udp;
    
    template
    class udp_sock
    {
        public:
            udp_sock(std::string host, unsigned short port);
        private:
            static udp::endpoint build_ep(const std::string &host,
              unsigned short port, boost::asio::io_service &io_service);
    
            boost::asio::io_service _io_service;
            udp::socket _sock;
            boost::array _buf;
    };
    
    template
    udp::endpoint udp_sock::build_ep(const std::string &host,
      unsigned short port, boost::asio::io_service &io_service)
    {
        udp::resolver res(io_service);
        udp::resolver::query query(udp::v4(), host, "spec");
        udp::endpoint ep = *res.resolve(query);
        ep.port(port);
        return ep;
    }
    
    template
    udp_sock::udp_sock(std::string host = "localhost",
      unsigned short port = 50000)
        : _sock(_io_service, build_ep(host, port, _io_service))
    {
    }
    

提交回复
热议问题