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

后端 未结 8 608
一生所求
一生所求 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:41

    You could turn the _sock member into a smart pointer:

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

提交回复
热议问题