C++ 提升 ASIO:在类内初始化io_context:

C++ Boost ASIO: initializing io_context inside class:

本文关键字:io 初始化 context 提升 ASIO C++      更新时间:2023-10-16

我在这里遵循 Boost UDP 组播发送器教程. 我修改它以创建一个类,如下所示:

#define _CRT_SECURE_NO_WARNINGS
#include <ctime>
#include <iostream>
#include <string>
#include <boost/array.hpp>
#include <boost/bind.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/asio.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/thread.hpp>
using boost::asio::ip::udp;
using std::cout;
using std::cin;
using std::endl;
class sender
{
private:
    boost::asio::io_context io_context;
    boost::asio::ip::udp::endpoint endpoint_;
    boost::asio::ip::udp::socket socket_;
    int message_count_;
    std::string message_;
    bool showBroadcast;
public:
    // constructor
    sender(std::string multicast_address, unsigned short multicast_port, bool show = true)
    {
        boost::asio::io_context io_context;
        boost::asio::ip::udp::endpoint endpoint_(boost::asio::ip::make_address("192.168.0.255"), 13000);
        boost::asio::ip::udp::socket socket_(io_context, endpoint_.protocol());
        socket_.set_option(boost::asio::ip::udp::socket::reuse_address(true));  // no need
    }
    // destructor
    ~sender()
    {
        cout << "UDP sender exiting." << endl;
    }
private:
    std::string get_input()
    {
        std::string result;
        cout << "Enter your message: ";
        getline(cin, result);
        return result;
    }
    std::string make_daytime_string()
    {
        using namespace std; // For time_t, time and ctime;
        time_t now = time(0);
        std::string result = ctime(&now);
        return result.erase(result.length() - 1, 1);
    }
    std::string some_string()
    {
        std::string result;
        result = make_daytime_string();
        return result;
    }
};
int main(int argc, char* argv[])
{
    try
    {
        sender s("192.168.0.255", 13000);
    }
    catch (std::exception& e)
    {
        std::cerr << "Exception: " << e.what() << "n";
    }
    return 0;
}

我希望将io_context对象封装在类中,而不是将其封装在外部。 VC++抱怨:

boost::

asio::basic_datagram_socket':没有合适的默认构造函数可用

我相信它试图迫使我拥有如下构造函数(我试图摆脱它(:

    sender(boost::asio::io_context& io_context, const boost::asio::ip::address& multicast_address, unsigned short multicast_port, bool show = true) 
    : endpoint_(multicast_address, multicast_port),
    socket_(io_context, endpoint_.protocol())

我怎么可能把所有东西都封装在我的课堂里? 为什么 Boost 强迫我做另一种方式? 请帮忙。 非常感谢。

这似乎是由于io_context是不可复制的,如此处的建议. 我希望这个类是可复制的。 知道吗?

没有一个 ASIO 类是可复制的,大多数都包含io_context引用,因此需要使用一个引用来构造。如果您希望类可复制,则需要使用指向 ASIO 对象的共享指针。我不确定您为什么要复制 ASIO 对象,因为无论如何您都不能一次从多个位置使用它们。