我知道我们可以在一些函数中指定streambuf的大小,如下所示
boost::asio::streambuf bufferstrm(512);但是在课堂上我们怎么能做同样的事情呢?
class test{
public:
boost::asio::streambuf bufferstrm;
void func1(){
//statement
}
void func2(){
//statement
}
};所以我的问题是,如果我们在上面的类中声明了boost::asio::streambuf bufferstrm;,那么我们如何指定bufferstrm的大小,以便它可以被类的所有函数使用。
我尝试了下面的代码
class test{
public:
boost::asio::streambuf bufferstrm(1024); // specified the size
void func1(){
//statement
}
void func2(){
//statement
}
};但它给出的错误是无法在声明点处初始化。
发布于 2021-03-25 03:37:37
您可以在C++14和更高版本中以正确的语法使用NSMI :
class test {
public:
boost::asio::streambuf bufferstrm { 1024 }; 实际上,这只不过是构造函数初始化器列表项in c++03 style的简写
class test {
public:
boost::asio::streambuf bufferstrm;
test()
: bufferstrm (1024) // base/member initializer list
{}子类
还可以考虑创建添加初始化的派生类型。
更新子类的想法
事实证明,让一个子类实际使用API的消费缓冲区并不是那么简单,因为所有API都在streambuf参数上执行类型推导。类型推导不考虑到基类的转换,因此它无法识别从streambuf派生的类。此外,您还需要这些重载,因为streambuf是唯一通过引用获取的缓冲区类型。
我可以看到两种解决方案:
basic_streambuf<myalloc>来提供到basic_streambuf_ref<>转换为basic_streambuf_ref<>
您必须显式地调用它,但这可能还不是最糟糕的:
struct mystreambuf : boost::asio::streambuf
{
using base_type = boost::asio::streambuf;
mystreambuf() : base_type{1024} {}
auto ref()
{
return boost::asio::basic_streambuf_ref<std::allocator<char>>{
*static_cast<base_type*>(this)};
}
};用作:
using boost::asio::ip::tcp;
tcp::socket sock(boost::asio::system_executor{}, {{}, 7878});
mystreambuf msb;
read_until(sock, msb.ref(), "\r\n\r\n");被黑客入侵的分配器
template <typename T>
struct myalloc : std::allocator<T> {};
template <typename T>
struct boost::asio::basic_streambuf<myalloc<T>>
: boost::asio::basic_streambuf<std::allocator<T>>
{
basic_streambuf() : base_type(1024) {}
using base_type = boost::asio::basic_streambuf<std::allocator<T>>;
using base_type::base_type;
using base_type::operator=;
};
using mystreambuf1024 = boost::asio::basic_streambuf<myalloc<char>>;然后可以将其用作
mystreambuf1024 msb;
read_until(sock, msb, "\r\n\r\n");https://stackoverflow.com/questions/66787704
复制相似问题