C++ 提升 ASIO:在类内初始化io_context:
C++ Boost ASIO: initializing io_context inside class:
我在这里遵循 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 对象,因为无论如何您都不能一次从多个位置使用它们。
相关文章:
- 是否可以初始化不可复制类型的成员变量(或基类)
- C++使用整数的压缩数组初始化对象
- C++初始化基类
- 多成员Constexpr结构初始化
- 复制列表初始化的隐式转换的等级是多少
- 内联映射初始化的动态atexit析构函数崩溃
- 如何在C++中初始化嵌套类中的2个memeber
- 如何声明特征矩阵,然后通过嵌套循环初始化它
- 没有用于初始化C++中的变量模板的匹配构造函数
- 在未初始化映射的情况下,将值插入到映射的映射中
- C++成员初始化
- 为什么在C++中首先初始化成员类
- 同时具有"聚合初始化"和"模板推导"
- 初始化具有非默认构造函数的std::数组项的更好方法
- 是否可以在编译时初始化数组,以便在运行时不会花费时间?
- 我可以使用条件运算符初始化C风格的字符串文字吗
- 在C和C++中初始化结构中的数组
- 标准是否使用多余的大括号(例如 T{{{10}}})定义列表初始化?
- 在函数内部的声明中初始化数组,并在外部使用它
- 继承:构造函数,初始化C++11中基类的类C数组成员