I get the following error message when I'm trying to use std::string with boost::asio::buffer:
boost/asio/detail/consuming_buffers.hpp:
In constructor
'boost::asio::detail::consuming_buffers<
boost::asio::mutable_buffer, boost::asio::const_buffers_1
>::consuming_buffers(const boost::asio::const_buffers_1 &)':
boost/asio/impl/read.hpp:140:25:
instantiated from
'boost::asio::detail::read_op<
boost::asio::basic_stream_socket<boost::asio::ip::tcp>,
boost::asio::const_buffers_1
, boost::asio::detail::transfer_all_t
, boost::_bi::bind_t<
void, boost::_mfi::mf1<void, read_op, const
boost::system::error_code &>
, boost::_bi::list2<boost::_bi::value<read_op
*>, boost::arg<1> (*)()>
>
>::read_op(
boost::asio::basic_stream_socket<boost::asio::ip::tcp>
&, const boost::asio::const_buffers_1
&
, boost::asio::detail::transfer_all_t
, boost::_bi::bind_t<
void, boost::_mfi::mf1<void, read_op, const
boost::system::error_code &>
, boost::_bi::list2<boost::_bi::value<read_op
*>, boost::arg<1> (*)()>
>
)'
[...]
Full source code: http://liveworkspace.org/code/eca749f6f2714b7c3c4df9f26a404d86
I think the problem is that you are passing a const buffer to async_read instead of a mutable buffer. In the block ending in line 50, boost::asio::buffer(_header) returns a const buffer. You should do something like boost::asio::async_read(s, boost::asio::buffer(data, size), handler), because boost::asio::buffer(data, size) creates a mutable buffer.
Instead of using std::strings for _header and _data, you probably need to use arrays of char, such as:
char* _data;
boost::asio::buffer(_data, strlen(_data));
See reference documentations for buffer and async_read.
You must pass a pointer as the first parameter:
#include <string>
#include <boost/asio.hpp>
std::string request, reply;
auto rsize = boost::asio::buffer(&reply[0], request.size());
From the boost::asio::buffer reference documentation:
It seems that std::string could only be passed into an asio::buffer as a const reference.
std::vector<char> should be a better alternative:
std::vector<char> d2(128);
bytes_transferred = sock.receive(boost::asio::buffer(d2));
Related
The compiler wants my lvalue to be a rvalue reference and I dont see why.
My questions are:
Why is "dataLen" const, even though it was declared non const and the lambda is told to catch by reference as default?
Why does the compiler try to convert to rvalue reference "unsigned __int64 &&", even though it was declared "unsigned long long" (no rvalue reference) for tupleByteVector_content?
I think it is because of the lambda capture, but please see this simplified workflow below:
void read_socket()
{
std::vector<std::tuple<unsigned long long, std::vector<unsigned char>>> tupleByteVector_content;
read_socket_readSome(tupleByteVector_content, [this, &tupleByteVector_content]() {
//use tuple vector
});
}
//catch the tuple vector by reference
void read_socket_readSome(std::vector<std::tuple<unsigned long long, const std::shared_ptr<Session>& session, std::vector<unsigned char>>> & tupleByteVector_content, std::function<void()> && continueReadFunction)
{
//Read data length from a asio socket
std::shared_ptr<asio::streambuf> len_buffer = std::make_shared<asio::streambuf>();
asio::async_read(session->connection->socket->next_layer(), *len_buffer, asio::transfer_exactly(1), [&,
this, session, len_buffer, tupleByteVector_content, continueReadFunction](const error_code& ec, std::size_t bytes_transferred) {
//the first value I want to save
unsigned long long dataLen = BytesToLength(len_buffer);
//Read data from a asio socket
std::shared_ptr<asio::streambuf> data_buffer = std::make_shared<asio::streambuf>();
asio::async_read(session->connection->socket->next_layer(), *data_buffer, asio::transfer_exactly(dataLen), [&, this, dataLen, data_buffer, tupleByteVector_content, session, continueReadFunction](const error_code& ec, std::size_t bytes_transferred) {
//ERROR HERE: ----------->
std::tuple<unsigned long long, std::vector<unsigned char>> t =
std::make_tuple<unsigned long long, std::vector<unsigned char>>(
dataLen, // ERROR C2664, cant convert argument 1 from "const unsigned __int64" to "unsigned __int64 &&"
{ asio::buffers_begin(data_buffer->data()), asio::buffers_end(data_buffer->data()) });
//ERROR HERE: <-----------
tupleByteVector_content.push_back(t);
continueReadFunction();
});
});
}
EDIT:
I was able to compile this tuple:
std::tuple<unsigned long long, std::vector<unsigned char>> t = { dataLen, { asio::buffers_begin(data_buffer->data()), asio::buffers_end(data_buffer->data()) } };
But then the push_back to the vector gives the error:
error C2663: [...] ::push_back": for 2 overloads there is no conversion for the this-pointer (free translation into english from myself)
dataLen is treated as const because you capture it by value:
[&, this, dataLen,
^^^
By default function call operator generated for closure is marked as const, so inside const method you can only read data. Modifications are not allowed, unless you add mutable to definition of lambda.
When you use make_tuple you should rely on template argument deduction instead putting types in explicit way, as you did it. Short version of your issue:
int i;
std::tuple<int> t = std::make_tuple<int>(i);
i is named object, so it is lvalue. By make_tuple<int> you make make_tuple signature look like: make_tuple(int&&). This is the place where compiler complains, because i as lvalue cannot be bound to rvalue reference. With argument deduction, parameter of make_tuple is deduced to be: int&, and in this case i can be bound.
push_back on vector doesn't work, because again you captured vector by value. push_back modifies object, which is not allowed when calling on const object. You should capture it by reference.
The current C++ compilers fail to find a suitable overload for std::shared_ptr when using a C-array as a type.
I can make it a real std::array object and that works, but the library I'm linking against (fftw3) has already created the typedef and uses it in all of it's C-API calls.
#include <memory>
typedef double fftw_complex[2];
int main(int argc, char* argv[])
{
fftw_complex bob; //works fine
bob[0]=2; bob[1]=-1; //works fine
std::shared_ptr<fftw_complex> handle; //works fine
std::shared_ptr<double> other(new double[35]); //works fine
handle = std::shared_ptr<fftw_complex>(new fftw_complex[35]);//can't find constructor
return 0;
}
Up until a few months ago this worked fine with all compilers. With the update to gcc to version 7.3, 8.2, and 9 I now get an error when trying to compile the non-void constructor. I suspect it is because of the "improvements" to std::shared_ptr to automatically handle when T is an array type.
I get the error
complex_shared.cpp:12:61: error: no matching function for call to 'std::shared_ptr<double [2]>::shared_ptr(double (*)[2])'
12 | handle = std::shared_ptr<fftw_complex>(new fftw_complex[35]);
and the somewhat difficult to parse error message
note: candidate: 'template<class _Yp, class> std::shared_ptr<_Tp>::shared_ptr(_Yp*)'
139 | shared_ptr(_Yp* __p) : __shared_ptr<_Tp>(__p) { }
| ^~~~~~~~~~
/usr/local/Cellar/gcc/9.2.0/include/c++/9.2.0/bits/shared_ptr.h:139:2: note: template argument deduction/substitution failed:
/usr/local/Cellar/gcc/9.2.0/include/c++/9.2.0/bits/shared_ptr.h: In substitution of 'template<class _Tp> template<class ... _Args> using _Constructible = typename std::enable_if<std::is_constructible<std::__shared_ptr<_Tp>, _Args ...>::value>::type [with _Args = {double (*)[2]}; _Tp = double [2]]':
/usr/local/Cellar/gcc/9.2.0/include/c++/9.2.0/bits/shared_ptr.h:137:30: required from here
/usr/local/Cellar/gcc/9.2.0/include/c++/9.2.0/bits/shared_ptr.h:106:8: error: no type named 'type' in 'struct std::enable_if<false, void>'
106 | using _Constructible = typename enable_if<
it seems you have to let std::shared_ptr know that this is not a normal pointer but is indeed a pointer to an array
#include <memory>
typedef double fftw_complex[2];
int main(int argc, char* argv[])
{
fftw_complex bob;
bob[0]=2; bob[1]=-1;
std::shared_ptr<fftw_complex[]> handle;
std::shared_ptr<double> other(new double[35],[](double* p){ delete[] p;});
std::shared_ptr<double[]> nother(new double[35]); //std::shared_ptr will call delete[]
handle = std::shared_ptr<fftw_complex[]>(new fftw_complex[35], [](fftw_complex* p){ /* special delete logic*/;});
return 0;
}
to be clear, I have to use the fftw_malloc and fftw_free functions for this memory, so I will be providing my own deleter for the fftw_complex type. delete[] is incorrect for these library-provided data elements.
So I am having an issue using basename for one of my programming assignments for school
I have tried getting a simplier version of it working -- I got it working however, still confused exactly what I am supposed to do in this case
// $Id: util.cpp,v 1.1 2016-06-14 18:19:17-07 - - $
#include <libgen.h>
#include <cstring>
using namespace std;
#include "util.h"
ydc_exn::ydc_exn (const string& what): runtime_error (what) {
}
string exec::execname_; // Must be initialized from main().
int exec::status_ = EXIT_SUCCESS;
void exec::execname (const string& argv0) {
execname_ = basename (argv0.c_str());
cout << boolalpha;
cerr << boolalpha;
DEBUGF ('Y', "execname = " << execname_);
}
void exec::status (int new_status) {
new_status &= 0xFF;
if (status_ < new_status) status_ = new_status;
}
ostream& note() {
return cerr << exec::execname() << ": ";
}
ostream& error() {
exec::status (EXIT_FAILURE);
return note();
}
Just trying to get the code to compile --- my error message in c++ is:
'
util.cpp:15:16: error: no matching function for call to 'basename'
execname_ = basename (argv0.c_str());
^~~~~~~~
/usr/include/libgen.h:40:7: note: candidate function not viable: 1st argument ('const std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>
>::value_type *' (aka 'const char *')) would lose const qualifier
char *basename(char *);
^
1 error generated.
make: *** [util.o] Error 1'
basename takes char* as argument, which is not const, meaning the function is allowed to modify the value.
const string& argv0 is const, meaning the value of argv0 must not be modified.
Thus you are not allowed to call basename with argv0.c_str() as parameter, as that would violate the const qualifier.
The error message is clear: 1st argument ... would lose const qualifier.
So either change argv0 to not be const (probably not a good idea), or change basename to take a const char* parameter (probably the better idea), or change basename to work with std::string instead of char* like the rest of your code (probably the best idea).
So apparently basename is a unix function that you cannot change. (Thanks Nevin!) From the manpage:
Both dirname() and basename() may modify the contents of path, so it may be desirable to pass a copy when calling one of these functions.
In that case I recommend creating a copy of argv0. The simplest way of doing this would be to change the signature of execname to this:
void exec::execname(std::string argv0)
I think that your central problem is including libgen.h as well as cstring. If you look at the prototypes for basename in those files, they're different. If you're building this on linux, you'll see a comment in the libgen.h version which should be enlightening.
https://pubs.opengroup.org/onlinepubs/9699919799/utilities/basename.html and
https://linux.die.net/man/3/basename are useful here too.
I suggest removing the #include <libgen.h> and trying again.
I want to define a callback by using std::function, the definition like below:
typedef std::function<void (const std::string &, const std::string &,
const bool, const bool)> Callback;
But it has a syntax error, what can I do to fix this issue?
You should include functional, to use function:
#include <functional>
Is there any way to get behavior like this?
// Some definition(s) of operator "" _my_str
// Some definition of function or macro MY_STR_LEN
using T1 = MY_STR_LEN("ape"_my_str);
// T1 is std::integral_constant<std::size_t, 3U>.
using T2 = MY_STR_LEN("aardvark"_my_str);
// T2 is std::integral_constant<std::size_t, 8U>.
It seems not, since the string literals are passed immediately to some_return_type operator "" _my_str(const char*, std::size_t); and never to a literal operator template (2.14.8/5). That size function parameter can't be used as a template argument, even though it will almost always be a constant expression.
But it seems like there ought to be some way to do this.
Update: The accepted answer, that this is not possible without an extra definition per literal, is accurate for C++11 as asked, and also C++14 and C++17. C++20 allows the exact result asked for:
#include <cstdlib>
#include <type_traits>
#include <string_view>
struct cexpr_str {
const char* ptr;
std::size_t len;
template <std::size_t Len>
constexpr cexpr_str(const char (&str)[Len]) noexcept
: ptr(str), len(Len) {}
};
// Essentially the same as
// std::literals::string_view_literals::operator""sv :
template <cexpr_str Str>
constexpr std::string_view operator "" _my_str () noexcept
{
return std::string_view(Str.ptr, Str.len);
}
#define MY_STR_LEN(sv) \
std::integral_constant<std::size_t, (sv).size()>
Reading C++11 2.14.8 carefully reveals that the "literal operator template" is only considered for numeric literals, but not for string and character literals.
However, the following approach seems to give you constexpr access to the string length (but not the pointer):
struct MyStr
{
char const * str;
unsigned int len;
constexpr MyStr(char const * p, unsigned int n) : str(p), len(n) {}
};
constexpr MyStr operator "" _xyz (char const * s, unsigned int len)
{
return MyStr(s, len);
}
constexpr auto s = "Hello"_xyz;
Test:
#include <array>
using atype = std::array<int, s.len>; // OK