开发者

c++: How to init members of std::pair in constructor

I have the following class:

typedef std::pair<boost::asio::ip::tcp::socket, boost::asio::ip::tcp::socket>  socket_pair;

class ConnectionPair {
private:
    socket_pair _sockPair;
public:
    ConnectionPair(boost::asio::io_service &ios);
}

How do I init the sockets in the pair in the constructor ? the following won't compile:

ConnectionPair::ConnectionPair(asio::io_service &ios):
    _ios(ios),  
    _sockPair(asio::ip::tcp::socket(ios), asio::ip::tcp::socket(ios)){
}

EDIT: Here is the compiler error. Enjoy:

/boost_1_47_0/boost/asio/basic_io_object.hpp: In copy constructor ‘boost::asio::basic_socket<boost::asio::ip::tcp, boost::asio::stream_socket_service<boost::asio::ip::tcp> >::basic_socket(const boost::asio::basic_socket<boost::asio::ip::tcp, boost::asio::stream_socket_service<boost::asio::ip::tcp> >&)’:

/boost_1_47_0/boost/asio/basic_socket.hpp:43:1:   instantiated from ‘std::pair<_T1, _T2>::pair(const _T1&, const _T2&) [with _T1 = boost::asio::basic_stream_socket<boost::asio::ip::tcp>, _T2 = boost::asio::basic_stream_socket<boost::asio::ip::tcp>]’
/devel/msm1/connection.cpp:8:67:   instantiated from here
/boost_1_47_0/boost/asio/basic_io_object.hpp:163:3: error: ‘boost::asio::basic_io_object<IoObjectService>::basic_io_object(const boost::asio::basic_io_ob开发者_开发技巧ject<IoObjectService>&) [with IoObjectService = boost::asio::stream_socket_service<boost::asio::ip::tcp>, boost::asio::basic_io_object<IoObjectService> = boost::asio::basic_io_object<boost::asio::stream_socket_service<boost::asio::ip::tcp> >]’ is private
/boost_1_47_0/boost/asio/basic_socket.hpp:43:1: error: within this context
In file included from /boost_1_47_0/boost/asio.hpp:30:0,


If the type is copy-constructible, your code would have worked. I guess (and only guess, because you didn't specify the compiler error) that a socket is not copy-constructible. Since std::pair does not allow in-place factories, you'll have to make your pair a pair of boost::optional's and use in-place factories. See the boost documentation for more details.


Does boost::asio::ip::tcp::socket support copy? I wouldn't expect it. And types in an std::pair must be copyable.


You can initialize the pair like you are trying to do, but you have a couple of other errors in your code.

  • No semi colon on the end of your class declaration.
  • _ios member variable does not exist.

Unfortunately I don't have boost installed, but this compiles for me using G++ 4.1.2

#include <utility>

typedef std::pair<int, int> socket_pair;

class ConnectionPair
{
private:
        socket_pair _sockPair;

public:
        ConnectionPair(const int x);
};

ConnectionPair::ConnectionPair(const int x):
        _sockPair(x, x)
{
}

int main(int argc, const char *argv[])
{
        ConnectionPair c(10);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜