gpt4 book ai didi

c++:如何在构造函数中初始化std::pair的成员

转载 作者:太空狗 更新时间:2023-10-29 20:17:09 28 4
gpt4 key购买 nike

我有以下类(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);
}

如何在构造函数中初始化对中的套接字?以下将无法编译:

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

编辑: 这是编译器错误。享受:

/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_object<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,

最佳答案

如果类型是可复制构造的,您的代码就可以工作。我猜想(而且只是猜想,因为你没有指定编译器错误)套接字不是可复制构造的。由于 std::pair 不允许就地工厂,你必须让你的对成为一对 boost::optional 并使用就地工厂。参见 the boost documentation了解更多详情。

关于c++:如何在构造函数中初始化std::pair的成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7530724/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com