Consider the following code for example.
string str = "Alice ate apples";
str.erase(0, 2)
Does erase function actually allocate new memory and copy the "ice ate apples" or does erase function do an in-place copy?
Consider the following code for example.
string str = "Alice ate apples";
str.erase(0, 2)
Does erase function actually allocate new memory and copy the "ice ate apples" or does erase function do an in-place copy?
I thought that conditional type could be declared using decltype
in template functions. But it seems not. Could anyone point out what's wrong with my test code?
#include <boost/type_index.hpp>
using boost::typeindex::type_id_with_cvr;
#define print_type(var) do { \
std::cout << type_id_with_cvr<decltype(var)>().pretty_name() << std::endl; \
} while(0)
template <typename T1, typename T2>
auto max(T1 a, T2 b) -> decltype(a < b ? b : a) {
decltype(a < b ? b : a) c = a < b ? b : a;
print_type(c);
return a < b ? b : a;
}
int main() {
int i = 10;
double d = 3.3;
decltype(i < d? d : i) r = i < d? d : i;
print_type(r); // -> double
std::cout << r << std::endl; // 10
}
I started off with a simple function template for extracting the bit patterns of integral types
:
template <class Type> std::string as_binary_string( Type value ) { static_assert( std::is_integral<Type>::value, "Integral type required." ); return std::bitset<sizeof( Type ) * 8>( value ).to_string(); }
The above works without issue as is. I then ported this into a class template
with some other functionality of the integral type
: size in bytes, the max number of bit combinations, & the number of bits this type has. I save the bit pattern
into an std::string
. The class template
worked without issue.
Then I came up with another function for doing something similar with floating point types
thanks to user iBug
.
template <class T> std::string float_as_binary_string( T value ) { static_assert(std::is_floating_point<T>::value, "Floating Point type required."); std::bitset<sizeof( T ) * CHAR_BIT> b; std::uint8_t buf[sizeof( T ) * CHAR_BIT]; std::memcpy( buf, &value, sizeof( T ) ); for ( int i = 0; i < sizeof( T ); ++i ) { std::uint8_t cur = buf[i]; int offset = i * CHAR_BIT; for ( int bit = 0; bit < CHAR_BIT; ++bit ) { b[offset] = cur & 1; ++offset; // Move to next bit in b cur >>= 1; // Move to next bit in array } } return b.to_string(); }
I am in the process of porting this into the same class template
.
I have two options: I could partially specialize
this class template
or the more preferred member function overload
that you can see below in this class template
template<class ArithmeticType>
class BinaryRep {
public:
static_assert(std::is_arithmetic<ArithmeticType>::value, "Type must be an Arithmetic Type.");
static const std::size_t sizeInBytes_ = sizeof( ArithmeticType );
static const std::size_t standardByteWidth_ = 8;
static const std::size_t numbits_ = sizeInBytes_ * standardByteWidth_;
private:
typedef typename std::make_unsigned<ArithmeticType>::type unsigned_t;
const static unsigned_t maxVal_ = -1;
ArithmeticType arTy_;
std::string strBitPattern_;
//std::vector<unsigned char> bitPattern_ { 0 };
public:
BinaryRep() : arTy_(0) {
}
explicit BinaryRep( const ArithmeticType& arTy ) : arTy_( arTy ) {
processBits( arTy_ );
}
void setVal( const ArithmeticType& arTy ) {
arTy_ = arTy;
processBits( arTy_ );
}
const std::string& getBitPattern() const {
return strBitPattern_;
}
void clearBits() {
strBitPattern_.clear();
}
static void showMeta() {
std::ostringstream ostr;
ostr << "Max Value: " << +maxVal_ << " ";
ostr << "Size in bytes: " << sizeInBytes_ << " ";
ostr << "Number of bits: " << numbits_ << "\n";
std::cout << ostr.str();
}
static const std::string getMeta() {
std::ostringstream ostr;
ostr << "Max Value: " << +maxVal_ << " ";
ostr << "Size in bytes: " << sizeInBytes_ << " ";
ostr << "Number of bits: " << numbits_ << "\n";
return ostr.str();
}
friend std::ostream& operator<<( std::ostream& out, const BinaryRep& val ) {
std::ostringstream ostring;
ostring << "Val: " << +val.arTy_ << " ";
ostring << "Bit Pattern: ";
ostring << val.strBitPattern_ << std::endl;
out << ostring.str();
return out;
}
private:
template<class BasicType = ArtithmeticType>
void processBits( BasicType bt = arTy_ ) {
strBitPattern_ = std::bitset<sizeof( BasicType ) * 8>( bt ).to_string();
}
// float
template<>
void processBits<float>( float value ) {
std::bitset<sizeof( ArithmeticType ) * CHAR_BIT> b;
std::uint8_t buf[sizeof( ArithmeticType ) * CHAR_BIT];
std::memcpy( buf, &value, sizeof( ArithmeticType ) );
for ( int i = 0; i < sizeof( ArithmeticType ); ++i ) {
std::uint8_t cur = buf[i];
int offset = i * CHAR_BIT;
for ( int bit = 0; bit < CHAR_BIT; ++bit ) {
b[offset] = cur & 1;
++offset; // Move to next bit in b
cur >>= 1; // Move to next bit in array
}
}
strBitPattern_ = b.to_string();
}
// double
template<>
void processBits<double>( double value ) {
std::bitset<sizeof( ArithmeticType ) * CHAR_BIT> b;
std::uint8_t buf[sizeof( ArithmeticType ) * CHAR_BIT];
std::memcpy( buf, &value, sizeof( ArithmeticType ) );
for ( int i = 0; i < sizeof( ArithmeticType ); ++i ) {
std::uint8_t cur = buf[i];
int offset = i * CHAR_BIT;
for ( int bit = 0; bit < CHAR_BIT; ++bit ) {
b[offset] = cur & 1;
++offset; // Move to next bit in b
cur >>= 1; // Move to next bit in array
}
}
strBitPattern_ = b.to_string();
}
};
However, there are 2 main issues:
1st issue: The above will compile, build and run if used as such:
int main() { BinaryRep<char> brc; brc.setVal( 5 ); std::cout << brc << std::endl; return 0; }
However if I try to use it this way:
int main() { BinaryRep<float> brf; brf.setVal( 1.0f ); std::cout << brf << std::endl; return 0; }
This will not compile and gives this MS Visual Studio 2017 CE error and I do know why!
1>------ Build started: Project: PracticeMath, Configuration: Debug Win32 ------ 1>PracticeMath.cpp 1>c:\program files (x86)\microsoft visual studio\2017 community\vc\tools\msvc\14.11.25503\include\type_traits(1008): error C2338: make_signed<T>/make_unsigned<T> require that T shall be a (possibly cv-qualified) integral type or enumeration but not a bool type. 1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.11.25503\include\type_traits(1072): note: see reference to class template instantiation 'std::_Change_sign<_Ty>' being compiled 1> with 1> [ 1> _Ty=float 1> ] 1>c:\users\skilz80\documents\visual studio 2017\projects\practicemath\practicemath\binaryrep.h(42): note: see reference to class template instantiation 'std::make_unsigned<ArithmeticType>' being compiled 1> with 1> [ 1> ArithmeticType=float 1> ] 1>c:\users\skilz80\documents\visual studio 2017\projects\practicemath\practicemath\practicemath.cpp(77): note: see reference to class template instantiation 'BinaryRep<float>' being compiled 1>Done building project "PracticeMath.vcxproj" -- FAILED. ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
When trying to instantiate this class template
as either a float
or double
type
, it is failing for these lines of code from within the class template
.
typedef typename std::make_unsigned<ArithmeticType>::type unsigned_t; const static unsigned_t maxVal_ = -1;
It can not make the deduced type of float
nor double
to be made as unsigned.
I need a work around for this issue; and it is starting to make me think I might need to partial specialize
this instead of using preferred function overload
.
2nd issue: If I'm not partially specializing
and able to stick with the member function overload
: within the showMeta()
and getMeta()
functions I do need to report the correct values.
static void showMeta() { std::ostringstream ostr; ostr << "Max Value: " << +maxVal_ << " "; ostr << "Size in bytes: " << sizeInBytes_ << " "; ostr << "Number of bits: " << numbits_ << "\n"; std::cout << ostr.str(); } static const std::string getMeta() { std::ostringstream ostr; ostr << "Max Value: " << +maxVal_ << " "; ostr << "Size in bytes: " << sizeInBytes_ << " "; ostr << "Number of bits: " << numbits_ << "\n"; return ostr.str(); }
Here SizeInBytes_
& numBits_
are self explanatory. The member maxVal
does not mean the max numerical value that the variable can represent, in this context it means the max number of binary bit combinational representations the variable type
can support. For a simple example a char
& and unsigned char
that is 1 byte
or 8 bits
in size can support 256
uniquely different binary bit representations...
At this point I'm not sure if I should stick with trying to overload
the member functions, or if I do need to partially specialize
this class template
and once I resolve that, its a matter of getting the right meta
values for floating point types
. I don't know how to resolve the issue with std::make_unsigned<Type>
for floating_point
types
. The final piece of information that is also viably important is how would you also calculate the maximum number of combinatorial binary representations
for floating point types
: float
& double
. For floating point types the most common types supported are by the IEEE standard
as they are the preferred floating point types. At this current stage the endian
is not an issue.
I have a class A
that takes an initializer_list
and stores it as a member variable.
class A
{
public:
A(std::initializer_list<std::string> il) :
m_il(il)
{}
std::initializer_list<std::string> m_il;
};
Another class B
has A
as a member variable that is default initialized using the initializer_list
class B
{
public:
B()
{
std::cout << *m_a.m_il.begin() << std::endl;
}
A m_a { "hello", "bye" };
};
Now when I run this code in main, it prints nothing.
int main()
{
B b;
}
Why did the code above not print hello
? Is my usage of std::initializer_list
incorrect?
I want to create the game of Peg Solitaire in C++. To do that I have created an 2D array which prints the values 0s and 1s (1s representing marbles on the board) I have created functions called setupBoard() and displayBoard() as:
void SolitaireGame::setupBoard() {
{
a = 8;
b = 8;
board = new int*[a];
for (int i = 1; i < a; i++)
board[i] = new int[b];
{
for (int y = 1; y < a; y++)
{
for (int x = 1; x < b; x++)
{
if ((y == 1 || y == 2 ||y == 6 || y == 7)
&& (x == 1 || x == 2 || x == 6|| x == 7))
{
board[x][y] = 2;
}
else if ((y == 4) && (x == 4))
{
board[x][y] = 0;
}
else
board[x][y] = 1;
}
}
}
}
}
void SolitaireGame::displayBoard()
{
cout << "The initial state of your board is: " <<endl << endl;
for (int y = 1; y < a; y++)
{
for (int x = 1; x < b; x++)
{
if (board[x][y] == 2)
cout << " \t";
else if (board[x][y] == 1)
cout << board[x][y] << "\t";
else if (board[x][y] == 0)
cout << board[x][y] << "\t";
else
cout << "idf_row_num"<<"\t";
}
cout << "\n\n";
}
}
Now I want to write a function which accepts the values from the user, i.e. the row and column number of the board to access a particular marble and move it to a different valid position on the board. After accepting the values from the user and checking the condition for a valid move, how do I print the board again?
Something is not working quite well for me. Is this the way to declare a class, that accepts only floating point template parameter?
template <typename T, swift::enable_if<std::is_floating_point<T>::value> = nullptr>
class my_float;
I fail to define methods outside this class. Doesn't compile, not sure why
What is the difference of an implicitly defined and explicitly declared default/copy constructors? Example:
struct road{
std::string id;
std::string type;
std::vector<int> nodes;
road() = default;
road(const & road c_road) = default;
road(road && m_road);
};
and
struct road{
std::string id;
std::string type;
std::vector<int> nodes;
road(road && m_road);
};
also what is the difference from defining my own constructors like
road::road(){}
road::road(const road & c_road):id(c_road.id)), type(c_road.type)),
nodes(c_road.nodes){}
My question is, do I need to explicitly declare a default contructor (= default; version) or should I just rely on the implicit one? Is any version faster or safer in any way? Is any version "wrong"?
What's the difference between having (as a parameter of a function ofc) an initializer_list const &some_value and then giving that value to something like a vector and initializer_list const some_value and doing the same? I'm trying to learn C++ all over again, but the concept of initialization lists and reference pointers are making it hard (I come from C).
I'm just confused, both can compile just fine... is the first one taking the address of the initializer list and passing the value of that address to the vector and the second one is just copying the values of the list? which one should I use in a situation like this (if I wanted to make a constructor function for a class that has vectors in it).
I'm benchmarking the use of Memory Pools, Vector and LinkedList for containing and iterating over a number of objects. I get the number of objects with std::cin and place it in an integer. Up to this point there's no error. Yet when the number I input equals 1000 it gives the next error:
Structure of main:
int main()
{
std::clock_t start;
double listAvg = 0.0;
double poolAvg = 0.0;
double vecAvg = 0.0;
int num;
std::cin >> num;
for(int i=0; i++ < 30)
{
start = std::clock();
listTest(num);
listAvg += ((std::clock() - start)/(double)(CLOCKS_PER_SEC/1000));
start = std::clock();
poolTest(num);
poolAvg += ((std::clock() - start)/(double)(CLOCKS_PER_SEC/1000));
start = std::clock();
vecTest(num);
vecAvg += ((std::clock() - start)/(double)(CLOCKS_PER_SEC/1000));
}
}
Number of objects: 1000
* * * Error in `./main': double free or corruption (out): 0x0000000000c86940 * * *
======= Backtrace: =========
/lib/x86_64-linux-gnu/libc.so.6(+0x777e5)[0x7f6efd4bb7e5]
/lib/x86_64-linux-gnu/libc.so.6(+0x8037a)[0x7f6efd4c437a]
/lib/x86_64-linux-gnu/libc.so.6(cfree+0x4c)[0x7f6efd4c853c]
./main[0x4024ab]
./main[0x402bd1]
./main[0x402840]
./main[0x40427e]
./main[0x4046f9]
/lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xf0)[0x7f6efd464830]
./main[0x401449]
======= Memory map: ========
00400000-00409000 r-xp 00000000 08:06 1876578 /home/ * /main
00608000-00609000 r--p 00008000 08:06 1876578 /home/ * /main
00609000-0060a000 rw-p 00009000 08:06 1876578 /home/ * /main
00c5d000-00c8f000 rw-p 00000000 00:00 0 [heap]
7f6ef8000000-7f6ef8021000 rw-p 00000000 00:00 0
7f6ef8021000-7f6efc000000 ---p 00000000 00:00 0
7f6efd444000-7f6efd604000 r-xp 00000000 08:05 1834632 /lib/x86_64-linux-gnu/libc-2.23.so
7f6efd604000-7f6efd804000 ---p 001c0000 08:05 1834632 /lib/x86_64-linux-gnu/libc-2.23.so
7f6efd804000-7f6efd808000 r--p 001c0000 08:05 1834632 /lib/x86_64-linux-gnu/libc-2.23.so
7f6efd808000-7f6efd80a000 rw-p 001c4000 08:05 1834632 /lib/x86_64-linux-gnu/libc-2.23.so
7f6efd80a000-7f6efd80e000 rw-p 00000000 00:00 0
7f6efd80e000-7f6efd824000 r-xp 00000000 08:05 1836566 /lib/x86_64-linux-gnu/libgcc_s.so.1
7f6efd824000-7f6efda23000 ---p 00016000 08:05 1836566 /lib/x86_64-linux-gnu/libgcc_s.so.1
7f6efda23000-7f6efda24000 rw-p 00015000 08:05 1836566 /lib/x86_64-linux-gnu/libgcc_s.so.1
7f6efda24000-7f6efdb2c000 r-xp 00000000 08:05 1834622 /lib/x86_64-linux-gnu/libm-2.23.so
7f6efdb2c000-7f6efdd2b000 ---p 00108000 08:05 1834622 /lib/x86_64-linux-gnu/libm-2.23.so
7f6efdd2b000-7f6efdd2c000 r--p 00107000 08:05 1834622 /lib/x86_64-linux-gnu/libm-2.23.so
7f6efdd2c000-7f6efdd2d000 rw-p 00108000 08:05 1834622 /lib/x86_64-linux-gnu/libm-2.23.so
7f6efdd2d000-7f6efde9f000 r-xp 00000000 08:05 656317 /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.21
7f6efde9f000-7f6efe09f000 ---p 00172000 08:05 656317 /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.21
7f6efe09f000-7f6efe0a9000 r--p 00172000 08:05 656317 /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.21
7f6efe0a9000-7f6efe0ab000 rw-p 0017c000 08:05 656317 /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.21
7f6efe0ab000-7f6efe0af000 rw-p 00000000 00:00 0
7f6efe0af000-7f6efe0d5000 r-xp 00000000 08:05 1834593 /lib/x86_64-linux-gnu/ld-2.23.so
7f6efe2a4000-7f6efe2a9000 rw-p 00000000 00:00 0
7f6efe2d1000-7f6efe2d4000 rw-p 00000000 00:00 0
7f6efe2d4000-7f6efe2d5000 r--p 00025000 08:05 1834593 /lib/x86_64-linux-gnu/ld-2.23.so
7f6efe2d5000-7f6efe2d6000 rw-p 00026000 08:05 1834593 /lib/x86_64-linux-gnu/ld-2.23.so
7f6efe2d6000-7f6efe2d7000 rw-p 00000000 00:00 0
7ffea1d71000-7ffea1d93000 rw-p 00000000 00:00 0 [stack]
7ffea1dc9000-7ffea1dcb000 r--p 00000000 00:00 0 [vvar]
7ffea1dcb000-7ffea1dcd000 r-xp 00000000 00:00 0 [vdso]
ffffffffff600000-ffffffffff601000 r-xp 00000000 00:00 0 [vsyscall]
Aborted (core dumped)
The asterisk is the path to the main executable.
It works with any other number of objects, even bigger ones.
I am given a task to write a C++ code for inserting intervals iteratively as key of a priority queue. Whenever i insert a new interval, i need to add an edge between two vertices in the DAG. Any pseudo code for this or any hints to write code for Priority queue and dag?
Here's the situation, I want to map Method
enum and lambda function to make a simple web server, but I'm stuck now.
I can't find a way to map enum and lambda funciton, can anyone give an example?
Also I tried to use function pointer, but I got segmentation fault
, so what's the correct way to do this trick?
Need your help, any help would be great appreciated.
method.cpp
enum class Method {
Delete = 0,
Get,
Head,
Post,
Put,
Connect,
Options,
Trace,
Patch,
Purge,
InternalMethodCount,
};
struct EnumClassHash
{
template <typename T>
std::size_t operator()(T t) const
{
return static_cast<std::size_t>(t);
}
};
dispatcher.cpp
// typedef void (*request_handler)(const Request &, Response &);
typedef void (*request_handler)(const Request &, Response &);
typedef Match self_type;
self_type &get(request_handler handler) {
_handlers.insert(std::make_pair(Method::Get, handler));
return *this;
}
std::unordered_map<Method, request_handler, EnumClassHash> _handlers;
main.cpp
simple_handler.crud_match(std::string("/ok"))
.get([&](const Request &request,Response &response){
response.body = request.url;
});
I've been trying to solve a problem concurrently, which fits the thread pool pattern very nicely. Here I will try to provide a minimal representative example:
Say we have a pseudo-program like this:
Q : collection<int>
while (!Q.empty()) {
for each q in Q {
// perform some computation
}
// assign a new value to Q
Q = something_completely_new();
}
I'm trying to implement that in a parallel way, with n-1
workers and one main thread. The workers will perform the computation in the inner loop by grabbing elements from Q
.
I tried to solve this using two conditional variables, work
, on which the master threads notifies the workers that Q has been assigned to, and another, work_done
, where the workers notify master that the entire computation might be done.
Here's my C++ code:
#include <iostream>
#include <mutex>
#include <condition_variable>
#include <queue>
#include <thread>
using namespace std;
std::queue<int> Q;
std::mutex mut;
std::condition_variable work;
std::condition_variable work_done;
void run_thread() {
for (;;) {
std::unique_lock<std::mutex> lock(mut);
work.wait(lock, [&] { return Q.size() > 0; });
// there is work to be done - pretend we're working on something
int x = Q.front(); Q.pop();
std::cout << "Working on " << x << std::endl;
work_done.notify_one();
}
}
int main() {
// your code goes here
std::vector<std::thread *> workers(3);
for (size_t i = 0; i < 3; i++) {
workers[i] = new std::thread{
[&] { run_thread(); }
};
}
for (int i = 4; i > 0; --i) {
std::unique_lock<std::mutex> lock(mut);
Q = std::queue<int>();
for (int k = 0; k < i; k++) {
Q.push(k);
}
work.notify_all();
work_done.wait(lock, [&] { return Q.size() == 0; });
}
for (size_t i = 0; i < 3; i++) {
delete workers[i];
}
return 0;
}
Unfortunately, after compiling it on OS X with g++ -std=c++11 -Wall -o main main.cpp
I get the following output:
Working on 0
Working on 1
Working on 2
Working on 3
Working on 0
Working on 1
Working on 2
Working on 0
Working on 1
Working on 0
libc++abi.dylib: terminating
Abort trap: 6
After a while of googling it looks like a segmentation fault. It probably has to do with me misusing conditional variables. I would appreciate some insight, both architectural (on how to approach this type of problem) and specific, as in what I'm doing wrong here exactly.
I appreciate the help
I have a function that deals with a movable-only instance that is a wrapper around something else. That object provides means of access to the wrapped object and some checks which require it to be non-copyable. (Use case is a table of values, where the dtor of the wrapper should assert that all values were were accessed)
I defined a custom ctor from the wrapped type and implemented the move ctor/assignment.
However I'm getting an error due to an attempted copy: error: 'Movable::Movable(Movable&)' is private within this context
It works fine in C++11 but I need portability to C++03. How can I do this without an explicit instantiation of the wrapper and moving it into the function?
MWE:
#include <boost/move/move.hpp>
#include <iostream>
class Movable{
BOOST_MOVABLE_BUT_NOT_COPYABLE(Movable)
public:
int i;
Movable(int j):i(j){}
Movable(BOOST_RV_REF(Movable) other) // Move constructor
: i(boost::move(other.i))
{}
Movable& operator=(BOOST_RV_REF(Movable) other) // Move assignment
{
if(this != &other)
i = boost::move(other.i);
return *this;
}
};
void bar(Movable mov){
mov.i = 22;
std::cout << mov.i;
}
int main(int argc, char* argv[])
{
bar(5);
return 0;
}
I am using ReadFile api to read hid device on windows.This function gives same data every time from input buffer after first successful operation and keep on firing same event.When i clear input buffer then it goes in blocking mode and does not respond to further input from device. So my question is how to use ReadFile to read hid device in synchronous mode or asynchronous mode to continue read data from device. I am facing this issue only when i am unable to clear buffer. But after cleared buffer device become unresponsive.
Is it possible to define a boost::geometry
object using a boost::variant
?
This code doesn't compile as it doesn't like the variant object used inside geom::read_wkt()
.
#include <boost/geometry.hpp>
#include <boost/geometry/geometries/point_xy.hpp>
#include <boost/geometry/geometries/linestring.hpp>
#include <boost/geometry/geometries/polygon.hpp>
#include <boost/variant/variant.hpp>
#include <boost/variant.hpp>
namespace geom = boost::geometry;
typedef geom::model::d2::point_xy<double> point_type;
typedef geom::model::linestring<point_type> linestring_type;
typedef geom::model::polygon<point_type> polygon_type;
typedef boost::variant
<
point_type,
linestring_type,
polygon_type,
>
geometryVariant;
int main() {
std::string wkt = "LINESTRING(0 0, 1 1, 2, 2)";
geometryVariant gv;
geom::read_wkt(wkt, gv);
return 0;
}
However, if I explicitly define the linestring_type
it works fine
int main() {
std::string wkt = "LINESTRING(0 0, 1 1, 2, 2)";
linestring_type ls;
geom::read_wkt(wkt, ls);
return 0;
}
So suppose we have this expression
auto x =Object.operator[][1,2,3,4];
I want my C++ code to insert the numbers 1 2 3 4 to a vector that is located inside the object my code is below.
class Object{
Object operator[](int temp){
this->x.push_back(temp);
return *this;
}
vector<int> x;
};
int main()
{
auto x =Object().operator[][1,2,3,4];
return 0;
}
This code doesnt compile. As far as i have understood i have to overload comma and [] but i cant figure out how to do this.I am new to C++.
I have this simple C++ code. It executes correctly in Microsoft Visual Studio 2017.
// Author: Herbert Schildt
// Modified: Qiang Hu
// File name: ~ftp/pub/class/cplusplus/Array/Array3.cpp
// Purpose: Use sqrs[][] -- two dimentional integer
// array to store integers from 1 to 10 and
// their squares.
// Ask user for a number, then look up this
// number in the array and then print out its
// corresponding square.
#include "stdafx.h"
#include <iostream>
#include <vector>
using namespace std;
int main()
{
// C++ allows for the initialization of arrays. In the following,
// we are initializing a 10x2 integer array. After initialization,
// sqrs[0][0] = 1
// sqrs[0][1] = 1
// sqrs[1][0] = 2
// sqrs[1][1] = 4
// and so on
vector<vector<int> > sqrs = { {1, 1},
{2, 4}, // The square of 2 is 4,and so on
{3, 9},
{4, 16},
{5, 25},
{6, 36},
{7, 49},
{8, 64},
{9, 81},
{10, 100}
};
int i, j;
cout << "Enter a number between 1 and 10: ";
cin >> i;
// look up i
for(j = 0; j < 10; j++)
if(sqrs[j][0] == i) break; // break from loop if i is found
cout << "The square of " << i << " is " ;
cout << sqrs[j][1] << endl;
return 0;
}
I tried to use VSCode under windows to compile the same code but the code does not execute. It gives me the following error.
Untitled-2.cpp: In function 'int main()':
Untitled-2.cpp:34:19: error: in C++98 'sqrs' must be initialized by constructor, not by '{...}'
};
^
Untitled-2.cpp:34:19: required from here
Untitled-2.cpp:34:19: warning: extended initializer lists only available with -std=c++11 or -std=gnu++11
I guess that the compiler that VSCode is using is not C++11 but is C++98. If this is the case how can I change the compiler to C++11. (Here, I was looking for a solution but never find something useful.) If not, how to fix this problem?
I have these two functions, with duplicated exception treatment, which has the sole purpose of displaying an error message:
void func1() noexcept {
try {
do_task();
do_another_task();
} catch (const std::out_of_range& e) {
show_msg("Out of range error", e.what());
} catch (const std::logic_error& e) {
show_msg("Logic error", e.what());
} catch (const std::system_error& e) {
show_msg("System error", e.what());
} catch (const std::runtime_error& e) {
show_msg("Runtime error", e.what());
} catch (const std::exception& e) {
show_msg("Generic error", e.what());
}
}
void func2() noexcept {
try {
do_something();
do_something_else();
do_even_more();
} catch (const std::out_of_range& e) {
show_msg("Out of range error", e.what());
} catch (const std::logic_error& e) {
show_msg("Logic error", e.what());
} catch (const std::system_error& e) {
show_msg("System error", e.what());
} catch (const std::runtime_error& e) {
show_msg("Runtime error", e.what());
} catch (const std::exception& e) {
show_msg("Generic error", e.what());
}
}
I could just handle std::exception
and show a single generic message, but I want to be more specific, that's why I'm catching all possible exceptions.
I want to reuse this exception treatment code. I thought about this:
void run_treated(std::function<void()> func) noexcept {
try {
func();
} catch // ... all the catches go here
}
void func1() noexcept {
run_treated([]()->void {
do_task();
do_another_task();
});
}
void func2() noexcept {
do_something();
do_something_else();
do_even_more();
}
run_treated
will be called a lot. Should I be concerned about performance?I'm programing a phonebook and there is something wrong in reading from the file. the error is: no match for 'operator>>' (operand types are 'std::basic_istream' and '') [on hold]
void PhoneBook::Load()
{
ifstream file("test.txt");
//how i can make it(reading from file)correct?
if (file.is_open())
{
file>>contact.first>>endl
>>contact.last>>endl
>>contact.areacode>>endl
>>contact.number>>endl
>>contact.email>>endl
>>contact.webaddr>>endl
>>contact.address;
}
else
cout<<"error in openening file";
}
I'm getting a little confused about constant. It says here in Programming Principles and Practice Using C++ book that you cannot give a new value to constant.
constexpr int max = 17;
int val = 19;
max+2
but this code is confusing me. max+2, that means the max will have a new value, 19, so what really is constant? how come you can add 2 to a constant?
Is there a way to make the following work avoiding inheritance?
A
and B
share the same API, all I want to do is to obtain the underlying value and call on that the common member function.
#include <iostream>
#include <cstdlib>
#include <boost/variant.hpp>
struct A {
void foo(){
std::cout << "A" << std::endl;
}
};
struct B {
void foo(){
std::cout << "B" << std::endl;
}
};
template <typename Ret>
Ret getUnderlying(auto t) {
switch (t.which()){
case 0: return boost::get<A>(t);
case 1: return boost::get<B>(t);
}
}
int main()
{
using AB = boost::variant<A,B>;
AB var;
var = A();
getUnderlying(var).foo();
}
Error:
clang++ -I. -MMD -I/usr/local/Cellar/verilator/3.900/share/verilator/include -I/usr/local/Cellar/verilator/3.900/share/verilator/include/vltstd -DVL_PRINTF=printf -DVM_COVERAGE=0 -DVM_SC=0 -DVM_TRACE=0 -Wno-char-subscripts -Wno-parentheses-equality -Wno-sign-compare -Wno-uninitialized -Wno-unused-parameter -Wno-unused-variable -fbracket-depth=4096 -Qunused-arguments -std=c++11 -I../../../../common -lncurses -c -o blinky.o ../../../simulator/blinky.cpp
../../../simulator/blinky.cpp:24:12: error: use of undeclared identifier
'tolower'
switch(tolower(userCh)) {
^
My CFLAGS
are -std=c++11 -I../../../../common -lncurses
What am I doing wrong?
First some context, i got two nodejs native addon. The first one contains a static c++ object "Conn" exposed using an v8 object internal field as described in the embedder's guide
NAN_METHOD(cobject) {
auto isolate = Isolate::GetCurrent();
Conn* p = &ConnHolder::connection;
Local<ObjectTemplate> conn_templ = ObjectTemplate::New(isolate);
conn_templ->SetInternalFieldCount(1);
Local<Object> obj = conn_templ->NewInstance();
obj->SetInternalField(0, External::New(isolate, p));
info.GetReturnValue().Set(obj);
}
In my other native addon, i'm loading the first one using c++ code and i expose a function called test containing two calls on the Conn object "callToDummyFunction()" and "callToFunctionWithMemberAccess()"
// persistent handle for the main addon
static Persistent<Object> node_main;
void Init(v8::Local<v8::Object> exports, v8::Local<v8::Object> module) {
Isolate* isolate = Isolate::GetCurrent();
HandleScope scope(isolate);
// get `require` function
Local<Function> require = module->Get(String::NewFromUtf8(isolate, "require")).As<Function>();
Local<Value> args[] = { String::NewFromUtf8(isolate, "path_to_my_addon\\addon.node") };
Local<Object> main = require->Call(module, 1, args).As<Object>();
node_main.Reset(isolate, main);
NAN_EXPORT(exports, test);
}
NAN_METHOD(test) {
Isolate* isolate = Isolate::GetCurrent();
HandleScope scope(isolate);
// get local handle from persistent
Local<Object> main = Local<Object>::New(isolate, node_main);
// get `cobject` function to get pointer from internal field
Local<Function> createdMain = main->Get(String::NewFromUtf8(isolate, "cobject")).As<Function>();
Local<Object> callResult = createdMain->Call(main, 0, nullptr).As<Object>();
Local<Object> self = info.Holder();
Local<External> wrap = Local<External>::Cast(self->GetInternalField(0));
void* ptr = wrap->Value();
// from there i get a pointer to my Conn object
Conn* con = static_cast<Conn*>(ptr);
conn->callToDummyFunction();
conn->callToFunctionWithMemberAccess();
info.GetReturnValue().Set(10);
}
Then i'm launching a nodejs session using "node", i load the first and second addon using two require calls and finally i'm calling the method test on the second addon.
The method test is executed, the call to "callToDummyFunction" is executed successfully but the call to "callToFunctionWithMemberAccess" crash and also kill the node session.
Ok, so what is the difference between "callToDummyFunction" and "callToFunctionWithMemberAccess" ?
bool Conn::callToDummyFunction()
{
cout << "callToDummyFunction" << endl;
return true;
}
bool Conn::callToFunctionWithMemberAccess()
{
cout << "callToFunctionWithMemberAccess " << someIntMember << endl;
return true;
}
So, it seems accessing a member of the Conn object generate an error and crash the node session. The node session does not output any message before crashing.
Can someone tell me why?
And/Or
How to get an error message ?
Is there a way to wrap the pattern into a general, template function?
template <typename C>
auto Begin(C&& c) -> ??? {
using std::begin;
return begin(std::forward<C>(c));
}
The question here is how to write the return type of the function here?
g++ version is 5.3.0.
#include <algorithm>
int main() {
return 0;
}
test$ time g++ test.cpp
real 0m0.203s
user 0m0.073s
sys 0m0.031s
test$ time g++ test.cpp --std=c++11
real 0m0.761s
user 0m0.554s
sys 0m0.130s
Similar results over multiple attempts.
I've recently observed that by initializing an array, the garbage values are all replaced by null terminators. This would appear to be inconsequential, but in a large program I don't think it would be preferable to spend resources on cleaning out an array. Now to be clear, I don't program large programs, that's why I'm asking, I'm just a beginner. However, when used properly, it would stand to reason that garbage values would be perfectly fine as long as there is always an explicitly placed terminator.
So then, should I take it as bible to always initialize my arrays, or should I consider whether I can get away with leaving the garbage values untouched?
This started out as a question of: "Why isn't it possible to explicitly instantiate an std::vector of std::unique_ptr?" as in:
template class std::vector<std::unique_ptr<int>>;
although following explicit instantiations and variables are fine:
template class std::vector<int>;
template class std::unique_ptr<int>;
int main() {
std::vector<int> ints;
std::vector<std::unique_ptr<int>> pointers;
}
But the question changed to: "What would be the alternatives?"
I'll post my though walk-through to answer both, since I didn't find a question that felt similar enough. I am also looking for alternatives, if any other.
I am trying to compile LLVM 5.0.0 from source on Windows 10 with Visual Studio 14.0 (2015).
I used the following cmake flags:
CMAKEOPTIONS += -D PYTHON_EXECUTABLE:PATH=$(PYTHON_PATH)/bin/python
CMAKEOPTIONS += -D LLVM_ENABLE_TERMINFO=0
CMAKEOPTIONS += -D LLVM_ENABLE_EH=1
CMAKEOPTIONS += -D LLVM_ENABLE_RTTI=1
CMAKEOPTIONS += -D LLVM_ENABLE_ASSERTIONS:BOOL=ON -D LLVM_ABI_BREAKING_CHECKS:STRING="FORCE_OFF"
The compilation fails with:
Severity Code Description Project File Line Suppression State Error C2039 'iterator_facade_base,0,1>
,std::forward_iterator_tag,llvm::PHINode const ,__int64,llvm::PHINode const *,llvm::PHINode const &>': is not a member of 'llvm::BasicBlock::phi_iterator_impl' (compiling source file S:\authama\3p-tmw\3p\derived\win64\LLVM5\llvm-debug\lib\Target\AMDGPU\Utils\AMDGPUBaseInfo.cpp) LLVMAMDGPUUtils s:\authama\3p-tmw\3p\derived\win64\llvm5\llvm-debug\include\llvm\ir\basicblock.h 294
Which points to:
290 bool operator==(const phi_iterator_impl &Arg) const { return PN == Arg.PN; }
291
292 PHINodeT &operator*() const { return *PN; }
293
294 using phi_iterator_impl::iterator_facade_base::operator++;
295 phi_iterator_impl &operator++() {
296 assert(PN && "Cannot increment the end iterator!");
297 PN = dyn_cast<PHINodeT>(std::next(BBIteratorT(PN)));
298 return *this;
299 }
The source compiles with GCC 4.9/Debian8, so I am guessing I missed something to do with setting up the compiler correctly. Any suggestions for me to try?
I'm writing an open source sqlite interface library (mSqliteCpp for instance) that uses c++ classes and types to correctly manage sqlite databases.
So far the library is heavily using TMP to build SQL
strings, but I found a possible issue that may somehow affect the efficiency of the library.
I'm using classes to manage Fields definitions, classes definitions, queries and statements. Basically to define a table or a SELECT
statement, one defines the fields using proper FieldDef<T>
objects, then pass them to a statement builder that returns the correctly formatted SQL statement.
For example:
auto fldId = sqlite::makeFieldDef("id", sqlite::FieldType::Integer());
auto fldName = sqlite::makeFieldDef("name", sqlite::FieldType::Text());
auto fldValue = sqlite::makeFieldDef("value", sqlite::FieldType::Real());
sqlite::statements::Select select("Table", fldId, fldName, fldValue);
ASSERT_EQ(select.string(), "SELECT id,name,value FROM Table;");
Note that each field is strongly typed by the FieldType
type passed to the makeFieldDef
function, but different fields with similar type can be exchanged. For this reason the SQL statement in the ASSERT
call is built at runtime.
I would like to have them built at compile time, at least under certain conditions. For example, developer could use a different class or maybe the constexpr
keyword. But at this time I've no idea if this could be achieved.
What are the possible patterns? Can strings be statically built through TMP? I'm using C++11/14.
Thank you.
I need simple example for plot building with gtkmm-plplot. I try to read official documentation but it is very hard for me. Can you show me how to build sinusoidal plot?
I have a class that I need to make thread-safe. I'm trying to do this by putting a unique lock at the top of every function in the class. The problem is that as soon as one function calls another function (in this class) the mutexes seem to lock each other, despite being in different functions. How can I stop this from happening?
So I am trying to build a "sanitizer" function to filter formatting arguments before they are forwarded to printf
.
template<typename A>
_CR_INLINE decltype(auto) sanitize_forward(A&& arg) {
return std::forward<A>(arg);
}
template<>
_CR_INLINE decltype(auto) sanitize_forward<std::string>(std::string&& arg) {
return std::forward<const char*>(arg.c_str());
}
So every std::string
is supposed to "decay" into a const char*
, in order to be properly formatted.
template<typename...Args>
_CR_INLINE void printf_safe(const std::string& format, Args&&...args) {
std::printf(format.c_str(), sanitize_forward<Args>(args)...);
}
I want the arguments to be perfectly forwarded to printf
, which is why I return std::forward
. But I can't really wrap my head around how this should be implemented.
1) Is decltype(auto)
correct? It should preserve the r-value referenceness of the return of std::forward
, right?
2) How should I specialize my template: std::string&&
or std::string
?
3) Deduced forwarding references should be the same as the actual type, right?
I am using the following constexpr GLenum array to represent GL_COLOR_ATTACHMENTx
(where x is an unsigned integer between 0 and 7):
constexpr std::array<GLenum, 8> opengl_color_attachment{GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2, GL_COLOR_ATTACHMENT3, GL_COLOR_ATTACHMENT4, GL_COLOR_ATTACHMENT5, GL_COLOR_ATTACHMENT6, GL_COLOR_ATTACHMENT7};
This works fine for only the first eight available color attachments (which the OpenGL specification states to be the minimum). However, there is a possibility of more attachments, which is implementation defined. As the macro GL_MAX_COLOR_ATTACHMENTS
represents the number of attachments available, I wanted to edit this constexpr array to include ALL available attachments to the limit, instead of the minimum of 8.
I created the following macro in an attempt to solve this issue myself:
#define OPENGL_COLOR_ATTACHMENT(x) GL_COLOR_ATTACHMENT##x
Although I wanted to use this in a constexpr function to create the array in compile-time, it failed because preprocessor macros are obviously processed before compilation. Although the OpenGL standard guarantees that GL_TEXTURE1 == GL_TEXTURE0 + 1
, it does not seem to guarantee this for the GL_COLOR_ATTACHMENTx macro.
Is there a way for me to create the constexpr array fully from GL_COLOR_ATTACHMENT0 to GL_COLOR_ATTACHMENTx where x = GL_MAX_COLOR_ATTACHMENTS, with or without preprocessor macros?
If I am passing a vector to a function as reference and I want the function should not modify the vector, what is better - using const vector<>
or using vector::const_iterator
?
For example, I am traversing through a vector passed from main()
to foo()
.
void foo (const vector<int> &v1) {
vector<int>::const_iterator m;
for(m=v1.begin();m1!=v1.end();++m1)
//loop body
}
And main()
is
int main() {
vector<int> v11={0,1,2,3,4};
foo(v11);
}
In this case, v1
should be const
or m
should be const_iterator
?
Hi Guys i am facing this list problem where i want to clone a list with random pointers. But my code is giving me this error while cloning pointers. here i am adding only the function code but i am also attaching the link for full code. the error is
Thread 1: EXC_BAD_ACCESS (code=1, address=0x8)
Node *createAnotherList(Node *head){
Node *temp = head, *start = head;
Node *firstPointer;
int count = 0;
while(temp != NULL){
Node *newNode = new Node;
newNode->data = temp->data;
newNode->random = NULL;
newNode->next = temp->next;
temp->next = newNode;
if(count == 0){
firstPointer = newNode;
count++;
}
temp = newNode->next;
}
// printList(list1);
while(start != NULL){
cout << start->data << " ";
if(start->next)
start->next->random = start->random->next;
start = start->next ? start->next->next : start->next;
}
return head;
}
i am getting error in 2nd while loop
start->next->random = start->random->next;
if someone knows what is the error please help me. and for more info please check the code from the link and error line is LINE 74
So I am trying to validate if all elements of a std::tuple
meet a certain condition. My current solution uses C++17 fold epxressions:
template <typename F, typename Tuple, size_t...Is>
_CR_INLINE bool tuple_all_of(F&& fn, Tuple&& t, std::index_sequence<Is...>) {
return (std::forward<F>(fn)(std::get<Is>(std::forward<Tuple>(t))) && ...);
}
template <typename F, typename Tuple>
_CR_INLINE bool tuple_all_of(F&& fn, Tuple&& t) {
return tuple_all_of(std::forward<F>(fn), std::forward<Tuple>(t),
std::make_index_sequence<std::tuple_size_v<std::remove_reference_t<Tuple>>>());
}
It compiles in latest clang and gcc, but fails in MSVC, because fold expressions are not (yet) implemented. (http://ift.tt/2q3O3xq)
So is there a similar solution without using fold expressions?
This is how it's supposed to be used:
template<typename...Components, typename Callable>
void FindComponents(Callable&& fn) {
for (auto& node : m_Entities) {
auto tp = std::make_tuple(node.GetComponent<Components>()...);
if (!tuple_all_of([](auto& p) { return p != nullptr; }, tp))
continue;
apply_from_tuple(fn, tp);
}
}
So I am calling fn
only if a node has the requested components attached (i.e. GetComponent
!= nullptr). Maybe there is a better solution?
I am trying to create function in separate header file but getting problem. Here is the code.
//printVec.cpp
#include<vector>
#include<iostream>
#include"printV.h"
void printVec(const std::vector<double> *v1)
{
std::vector<double>::const_iterator ele;
std::cout << "elements: \n";
for (ele = v1->begin(); ele != v1->end(); ++ele)
{
std::cout << *ele << " ";
}
}
//func1.cpp
#include <iostream>
#include<vector>
#include"printV.h"
int main()
{
std::vector<double> A={1,2,3,4,5,6,7,8,9,10};
//Displaying vector A and B
printVec(&A);
return 0;
}
This is header file.
//printV.h
#ifndef PRINTV_H
#define PRINTV_H
#include<vector>
void printVec(const std::vector<double> *v1);
#endif
I am compiling it using g++ -Wall -Wextra -I <path to header file> printVec.cpp func1.cpp -o prog_matmult -std=c++11
, but getting error as undefined reference to
printVec(std::vector > const*)' collect2.exe: error: ld returned 1 exit status `. Can someone comment what is problematic?
I've designed a pretty print/format library using template meta-programming that could print/format objects of any type, as long as they support certain concept(s). For that, I've few overloaded function templates (sfinae-enabled) and I'm using this library in lots of applications. It was working fine using gcc 4.7.3 with -std=c++11
.
Now I'm planning to upgrade and use gcc 7.1.0 & -std=c++17
. At one place I'm doing equivalent to this:
enum class bad_record;
auto s = pretty::format("%1%, %2%", "hello"s, bad_record{});
It results in lots of compilation errors, with really interesting diagnostic messages; "interesting" because one of the overloaded function template called try_print_nonptr()
instantiated twice, each time differently. First it gets instantiated as expected, i.e decltype(out << data, void())
is evaluated to be void
, and next time, the same expression is evaluated to be <type-error>
, as shown in bold in the error messages below.
I'm unable to reproduce this problem in a small code which I can post here. So I'd really appreciate if anyone could help me understand the scenarios in which such an isssue could come up, so that I can fix my code accordingly.
$gcc/7.1.0R6/include/c++/7.1.0/ostream:656:5: note: candidate: template<class _Ostream, class _Tp> typename std::enable_if<std::__and_<std::__not_<std::is_lvalue_reference<_Tp> >, std::__is_convertible_to_basic_ostream<_Ostream>, std::__is_insertable<_Ostream&, const _Tp&, void> >::value, typename std::__is_convertible_to_basic_ostream<_Tp>::ostream_type>::type std::operator<<(_Ostream&&, const _Tp&) operator<<(_Ostream&& __os, const _Tp& __x) ^~~~~~~~
$gcc/7.1.0R6/include/c++/7.1.0/ostream:656:5: note: template argument deduction/substitution failed: $gcc/7.1.0R6/include/c++/7.1.0/ostream: In substitution of 'template<class _Ostream, class _Tp> typename std::enable_if<std::__and_<std::__not_<std::is_lvalue_reference<_Tp> >, std::__is_convertible_to_basic_ostream<_Ostream>, std::__is_insertable<_Ostream&, const _Tp&, void> >::value, typename std::__is_convertible_to_basic_ostream<_Tp>::ostream_type>::type std::operator<<(_Ostream&&, const _Tp&) [with _Ostream = std::basic_ostream<char>&; _Tp = frap::common::bad_record]':
$/feut/pretty/details/print_impl.hpp:295:8: required from 'decltype (((out << data), void())) feut::pretty::details::try_print_nonptr(std::basic_ostream<_CharT, _Traits>&, const Item&, const feut::meta::preference<1>&) [with CharT = char; Traits = std::char_traits<char>; Item = frap::common::bad_record; decltype (((out << data), void())) = void]'
$/feut/pretty/details/print_impl.hpp:449:20: required from 'void feut::pretty::details::try_print(std::basic_ostream<Char, Traits>&, const Item&, const feut::meta::preference<5>&) [with Item = frap::common::bad_record; CharT = char; Traits = std::char_traits<char>; <template-parameter-1-4> = void]' $/feut/pretty/details/object_proxy.hpp:33:22: required from 'std::basic_ostream<Char, Traits>& feut::pretty::proxy_details::operator<<(std::basic_ostream<Char, Traits>&, const feut::pretty::proxy_details::object_proxy<T>&) [with T = frap::common::bad_record; CharT = char; Traits = std::char_traits<char>]' $/boost/format/feed_args.hpp:99:12:
required from 'void boost::io::detail::put_last(std::basic_ostream<_CharT, _Traits>&, const T&) [with Ch = char; Tr = std::char_traits<char>; T = feut::pretty::proxy_details::object_proxy<frap::common::bad_record>]' $/boost/format/feed_args.hpp:126:17: required from 'void boost::io::detail::call_put_last(std::basic_ostream<_CharT, _Traits>&, const void*) [with Ch = char; Tr = std::char_traits<char>; T = const feut::pretty::proxy_details::object_proxy<frap::common::bad_record>]' $/boost/format/feed_args.hpp:135:47: required from 'boost::io::detail::put_holder<Ch, Tr>::put_holder(T&) [with T = const feut::pretty::proxy_details::object_proxy<frap::common::bad_record>; Ch = char; Tr = std::char_traits<char>]' $/boost/format/feed_args.hpp:307:74: required from 'boost::basic_format<Ch, Tr, Alloc>& boost::io::detail::feed(boost::basic_format<Ch, Tr, Alloc>&, T) [with Ch = char; Tr = std::char_traits<char>; Alloc = std::allocator<char>; T = const feut::pretty::proxy_details::object_proxy<frap::common::bad_record>&]' $/boost/format/format_class.hpp:64:66: required from 'boost::basic_format<Ch, Tr, Alloc>& boost::basic_format<Ch, Tr, Alloc>::operator%(const T&) [with T = feut::pretty::proxy_details::object_proxy<frap::common::bad_record>; Ch = char; Tr = std::char_traits<char>; Alloc = std::allocator<char>]' $/feut/pretty/format.hpp:39:16:
required from 'std::string feut::pretty::format(const char*, const Args& ...) [with Args = {std::basic_string<char, std::char_traits<char>, std::allocator<char> >, frap::common::bad_record}; std::string = std::basic_string<char>]'$/frap/common/sec_analytics_file_reader.cpp:88:83: required from here
$gcc/7.1.0R6/include/c++/7.1.0/ostream:656:5: error: no type named 'type' in 'struct std::enable_if<false, std::basic_ostream<char>&>'
$/feut/pretty/details/print_impl.hpp: In instantiation of 'decltype (((out << data), void())) feut::pretty::details::try_print_nonptr(std::basic_ostream<_CharT, _Traits>&, const Item&, const feut::meta::preference<1>&) [with CharT = char; Traits = std::char_traits<char>; Item = frap::common::bad_record; decltype (((out << data), void())) = <type error>]':
$/feut/pretty/details/print_impl.hpp:449:20: required from 'void feut::pretty::details::try_print(std::basic_ostream<Char, Traits>&, const Item&, const feut::meta::preference<5>&) [with Item = frap::common::bad_record; CharT = char; Traits = std::char_traits<char>; <template-parameter-1-4> = void]' $/feut/pretty/details/object_proxy.hpp:33:22: required from 'std::basic_ostream<Char, Traits>& feut::pretty::proxy_details::operator<<(std::basic_ostream<Char, Traits>&, const feut::pretty::proxy_details::object_proxy<T>&) [with T = frap::common::bad_record; CharT = char; Traits = std::char_traits<char>]' $/boost/format/feed_args.hpp:99:12:
required from 'void boost::io::detail::put_last(std::basic_ostream<_CharT, _Traits>&, const T&) [with Ch = char; Tr = std::char_traits<char>; T = feut::pretty::proxy_details::object_proxy<frap::common::bad_record>]' $/boost/format/feed_args.hpp:126:17: required from 'void boost::io::detail::call_put_last(std::basic_ostream<_CharT, _Traits>&, const void*) [with Ch = char; Tr = std::char_traits<char>; T = const feut::pretty::proxy_details::object_proxy<frap::common::bad_record>]' $/boost/format/feed_args.hpp:135:47: required from 'boost::io::detail::put_holder<Ch, Tr>::put_holder(T&) [with T = const feut::pretty::proxy_details::object_proxy<frap::common::bad_record>; Ch = char; Tr = std::char_traits<char>]' $/boost/format/feed_args.hpp:307:74: required from 'boost::basic_format<Ch, Tr, Alloc>& boost::io::detail::feed(boost::basic_format<Ch, Tr, Alloc>&, T) [with Ch = char; Tr = std::char_traits<char>; Alloc = std::allocator<char>; T = const feut::pretty::proxy_details::object_proxy<frap::common::bad_record>&]' $/boost/format/format_class.hpp:64:66: required from 'boost::basic_format<Ch, Tr, Alloc>& boost::basic_format<Ch, Tr, Alloc>::operator%(const T&) [with T = feut::pretty::proxy_details::object_proxy<frap::common::bad_record>; Ch = char; Tr = std::char_traits<char>; Alloc = std::allocator<char>]' $/feut/pretty/format.hpp:39:16:
required from 'std::string feut::pretty::format(const char*, const Args& ...) [with Args = {std::basic_string<char, std::char_traits<char>, std::allocator<char> >, frap::common::bad_record}; std::string = std::basic_string<char>]'$/frap/common/sec_analytics_file_reader.cpp:88:83: required from here
There is global function (just example):
void func( int i )
{
std::cout << i + 100 << std::endl;
}
I assume that calling this function with char argument does not make any sense so I use delete:
void func(char) = delete;
So I expect that following calls should be possible:
func(1);
func(3.1);
func(true);
And call with char argument should be forbiden:
func('a');
But that is not true. When calling func('a')
I get as expected:
error: use of deleted function ‘void func(char)’
But during calling func(2.3)
I get:
error: call of overloaded ‘func(double)’ is ambiguous
I would like to find some programming errors concerning a GUI application with a QGraphicsView. To test manually, a mouse click onto the QGraphicsView component is required. Due to my imperfect mouse handling, various pixel coordinates result in a completely altered execution path with many changed variable values.
In addition, clicking manually for debugging purposes is rather time-expensive due to nasty errors (infinite loops, SIGSEVs, ...).
How is it possible to automate such a task like mouse-clicking similar to unit tests (with QTest) while being able to debug (control the program flow through breakpoints, ...)? Many thanks in advance.
I have been seen following type of code when i browsing Quora.
#include <iostream>
int f() { return 1; }
int main()
{
int (&var1)() = f;
using X = int(&)();
int i = reinterpret_cast<X>(var1)();
std::cout << " i = " << i << '\n';
}
So, What does using X = int(&)()
do?
I just found this: http://ift.tt/2DqG4OQ
But I don't know how to use it.
Is there some simple example?
I'm trying to create a small class that will allow me to facilitate a communication between two threads.
Those threads most probably will outlive the context in which the above mentioned class was created as they are queued onto a thread pool.
What I have tried so far (on coliru as well):
class A
{
public:
A(int maxVal) : maxValue(maxVal) {}
bool IsOverMax() const { return cur >= maxValue; }
void Increase() { cur++; }
private:
const int maxValue;
atomic_int cur{ 0 };
};
possible usage:
void checking(const shared_ptr<A> counter)
{
while(!counter->IsOverMax())
{
cout<<"Working\n"; // do work
std::this_thread::sleep_for(10ms);
}
}
void counting(shared_ptr<A> counter)
{
while (!counter->IsOverMax())
{
cout<<"Counting\n";
counter->Increase(); // does this fall under `...uses a non-const member function of shared_ptr then a data race will occur`? http://ift.tt/1jrtS5s
std::this_thread::sleep_for(9ms);
}
}
int main()
{
unique_ptr<thread> t1Ptr;
unique_ptr<thread> t2Ptr;
{
auto aPtr = make_shared<A>(100); // This might be out of scope before t1 and t2 end
t1Ptr.reset(new thread(checking, aPtr)); // To simbolize that t1,t2 will outlive the scope in which aPtr was originaly created
t2Ptr.reset(new thread(counting, aPtr));
}
t2Ptr->join();
t1Ptr->join();
//cout<< aPtr->IsOverMax();
}
The reason I'm concerned is that the documentation says that:
If multiple threads of execution access the same std::shared_ptr object without synchronization and any of those accesses uses a non-const member function of shared_ptr then a data race will occur unless all such access is performed through these functions, which are overloads of the corresponding atomic access functions (std::atomic_load, std::atomic_store, etc.)
Increase
is a non const function, are the copies of aPtr are the same std::shared_ptr
for this context or not ?I am trying through vector of vectors (2D vector) in C++. I used method from this answer. Here is code.
#include <iostream>
#include<vector>
void printVec(std::vector<std::vector<double>> *v1)
{
//displaying vector v1
std::vector <std::vector<double> >::const_iterator row;
std::vector<double>::const_iterator col;
std::cout<<"Displaying vectors";
for (row = v1->begin(), row != v1->end(); ++row) //error
{
for (col = row->begin(); col != row->end(); ++col)
{
std::cout << *col << " ";
}
std::cout <<std::endl;
}
}
int main()
{
int nRowA, nColA;
nRowA = 2;
nColA = 4;
std::vector< std::vector<double>> A, B, C;
std::vector<double> temp1;
//creating multidimensional vector A
for (int i = 0; i < nRowA; ++i)
{
for (int j = 0; j < nColA; ++j)
{
temp1.push_back(j+1);
}
A.push_back(temp1);
}
//Displaying vector A
printVec(&A);
return 0;
}
I am creating a vector in main()
is passing it by pointer to printVec()
. In printVec()
, I am using iterators to iterate through this 2D pointer. But getting error at the row indicated in the code as //error
. Can someone tell what is going wrong?
(I am aware about using range for loop and passing vector of vector as reference instead of as pointer. )
I may just be miss reading this code but in my attempt to call the default constructor, the code instead calls the copy constructor on my proposed creation.
Could someone give me a knowledge bomb on where my mental model and this code done meet :-/
Below is the code written, its a rough outline for a unique_handler that will hold data by a pointer defined by a trait. This is not relevant but the confusion is in why the auto h = new unique_handler(new My_handler());
performs a copy constructor call instead of a default constructor call.
#include "../psInclude/my_util.h"
namespace mlekena_smart_class{
template<typename Traits>
class unique_handle{
typedef typename Traits::pointer pointer;
pointer m_value;
//...
public:
// Delete the copy constructor
unique_handle(const unique_handle &u_handle) = delete;
explicit unique_handle(pointer value = Traits::invalid()) throw():
m_value(value)
{
}
auto get() const throw() -> pointer
{
// ...
}
auto release() throw() -> pointer
{
// ...
}
auto reset(pointer value = Traits::invalid) -> bool
{
// ...
}
~unique_handle() throw()
{
// ..
}
explicit operator bool() const throw()
{
// ..
}
};
struct null_handle_traits{
typedef HANDLE pointer;
// ...
}
using namespace mlekena_smart_class;
using namespace std;
struct My_handle{
int id;
const char* handle;
My_handle(int _id, const char* h): id(_id), handle(h){}
~My_handle(){}
};
int main(){
// offending code
auto h = null_handle{new My_handle(1, "Handler")};
// ...
}
}
I am using boost::python to call some python code from C++.
std::string input = "{\"x\":1}";
auto objectpath = boost::python::import("objectpath");
auto Tree = objectpath.attr("Tree")(input);
auto tree = Tree.attr("execute")("$..x");
In python the corresponding execution is (objectpath):
$ python
>>> from objectpath import *
>>> tree=Tree({"a":1})
>>> tree.execute("$.a")
1
But in C++ I am getting an error:
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/objectpath/core/interpreter.py", line 608, in execute
ret=exe(tree)
File "/usr/local/lib/python2.7/dist-packages/objectpath/core/interpreter.py", line 258, in exe
fst=exe(fst)
File "/usr/local/lib/python2.7/dist-packages/objectpath/core/interpreter.py", line 246, in exe
return self.data
AttributeError: 'Tree' object has no attribute 'data'
Python error, but failed to get the reason via PyErr
How can I fix my C++ problem?
I attempt to do debug logging to a file in one of the destructors. In our application, this happens to be on the GC [Finalizer] thread (since I want to do logging in our native library that is running in a managed context - a .NET application).
The problem is, that I can't construct std::ofstream
- it crashes during construction. Seems like std::locale::facet
object is already destroyed.
I attach a screenshot with a relevant call stack, code and an exception:
The bit of code that tries to create an ofstream
object is just that:
SpatialRenderer::~SpatialRenderer()
{
// dump
std::ofstream f("dump.txt"); // <- crash at this line
// writing to f here
}
Environment: Windows 10, Visual Studio 2017 Version 15.4.5
I want to toggle bits of an unsigned integer. Let us say I have an integer x. Why doesn't ~x return the number with toggled bits?
I completed my entire project on building an application that basically fetches sql query result based on some user input combination in the GUI and I believe that there is some performance issue when calling a Q_INVOKABLE
function in C++ code which performs some computation to produce the query and also run the query and return the result, so I wanted to know if there is a way to run that function in a separate thread from qml. The skeleton is somewhat like this:
Result.h
class Result{
public:
Q_INVOKABLE void on_submit_button_clicked();
}
Result.cpp
Result::on_submit_button_clicked()
{
/*Code that prepare the query*/
/*Code that runs the query using a Qthread*/
}
main.qml
ApplicationWindow
{
id:appwindow
/*Other parts of the GUI*/
Button{
id:submitButton
onClicked:{
result_object.on_submit_button_clicked() //how to run this function in a new thread ?
/*code to load my table view columns*/
}
}
}
I heard that cost of std::function
is heavier than auto
to deal with a lambda function. effective modern c++ item5. What I want is to clarify the mechanism why std::function
use more memory than auto
with some sample code. Could somebody help me?
#include <iostream>
#include <string>
using namespace std;
void chuli(string a)
{
a.erase(0,2);
}
int main()
{
string a = "012345";
a = chuli(a);
cout << a;
}
beginner for C++,i want to know why after this function,this string don't change.Is this something about the namespace?
Isn't the foll code given in C++ Primer incorrect ?
ostream_iterator<int> out_iter(cout, " ");
for (auto e : vec)
*out_iter++ = e; // the assignment writes this element to cout
cout << endl;
The postfix operator returns the old value, not a reference then how can it be made to act as an lvalue ?
Please correct if I am wrong
The following code does not compiler with GCC 5.2 or later, have not tried older compiler. Amy idea on what I am doing wrong here.
#include <iostream>
#include <string>
#include <type_traits>
template <typename T>
typename std::enable_if<std::is_enum<T>::value, T>::type
operator^=(T &lhs, const T &rhs)
{
lhs = static_cast<T>(
static_cast<typename std::underlying_type<T>::type>(lhs) ^
static_cast<typename std::underlying_type<T>::type>(rhs));
return lhs;
}
template <typename T, typename S>
typename std::enable_if<std::is_enum<T>::value && std::is_integral<S>::value, T>::type
operator^=(T &lhs, const S &rhs)
{
lhs = static_cast<T>(
static_cast<typename std::underlying_type<T>::type>(lhs) ^
static_cast<typename std::underlying_type<T>::type>(rhs));
return lhs;
}
enum Enum_t{
Red,
Blue,
Green,
Black
} ;
#define somedef 2
int main(){
Enum_t b = Red;
b ^= somedef;
std::cout << std::to_string(b) << std::endl;
}
I get the following error:
g++ -std=gnu++11 main.cpp
main.cpp: In function ‘int main()’:
main.cpp:34:4: error: invalid conversion from ‘int’ to ‘Enum_t’ [-fpermissive]
b ^= somedef;
I've worked a bit with processes in linux, and am now starting to work with windows. It seems to be a bit different as i'm getting a hard time finding the right way to get to what I want.
My question is: I need to iterate through some process's (specific PID that I already found) allocated pages under a page size condition. 1. How do I do such iteration? 2. Once i'm iterating, where can I find the page size?
I am on Ubuntu 16.04 LTS, and I have g++ working and have downloaded boost a few minutes ago.
I have a very simple cpp file that has #include <boost/thread.hpp>
in it. Compiling (running g++ -c -std=c++11 simple.cpp -o simple.o
) works, however, linking won't. I tried the following options:
g++ -std=c++11 -lpthread -lboost_system-lboost_thread simple.o -o simple
g++ -std=c++11 -L/usr/bin -L/usr/lib -I/usr/include -lpthread -lboost_system-lboost_thread simple.o -o simple
One thing worthy of mentioning is that /usr/include/boost
exists while /usr/lib/boost
does not.
I have installed boost using: sudo apt-get install libboost-all-dev
The error I get upon linking is:
simple.o: In function `__static_initialization_and_destruction_0(int, int)':
simple.cpp:(.text+0x132): undefined reference to `boost::system::generic_category()'
simple.cpp:(.text+0x13e): undefined reference to `boost::system::generic_category()'
simple.cpp:(.text+0x14a): undefined reference to `boost::system::system_category()'
simple.o: In function `boost::thread_exception::thread_exception(int, char const*)':
simple.cpp:(.text._ZN5boost16thread_exceptionC2EiPKc[_ZN5boost16thread_exceptionC5EiPKc]+0x23): undefined reference to `boost::system::system_category()'
simple.o: In function `boost::detail::thread_data_base::thread_data_base()':
simple.cpp:(.text._ZN5boost6detail16thread_data_baseC2Ev[_ZN5boost6detail16thread_data_baseC5Ev]+0x1e): undefined reference to `vtable for boost::detail::thread_data_base'
simple.o: In function `boost::thread::start_thread()':
simple.cpp:(.text._ZN5boost6thread12start_threadEv[_ZN5boost6thread12start_threadEv]+0x24): undefined reference to `boost::thread::start_thread_noexcept()'
simple.o: In function `boost::thread::~thread()':
simple.cpp:(.text._ZN5boost6threadD2Ev[_ZN5boost6threadD5Ev]+0x14): undefined reference to `boost::thread::detach()'
simple.o: In function `boost::thread::get_id() const':
simple.cpp:(.text._ZNK5boost6thread6get_idEv[_ZNK5boost6thread6get_idEv]+0x18): undefined reference to `boost::thread::native_handle()'
simple.o: In function `boost::thread::join()':
simple.cpp:(.text._ZN5boost6thread4joinEv[_ZN5boost6thread4joinEv]+0x88): undefined reference to `boost::thread::join_noexcept()'
simple.o: In function `Task::operator()()':
simple.cpp:(.text._ZN4TaskclEv[_ZN4TaskclEv]+0x67): undefined reference to `boost::this_thread::yield()'
simple.o: In function `boost::detail::thread_data<Task>::~thread_data()':
simple.cpp:(.text._ZN5boost6detail11thread_dataI4TaskED2Ev[_ZN5boost6detail11thread_dataI4TaskED5Ev]+0x20): undefined reference to `boost::detail::thread_data_base::~thread_data_base()'
simple.o:(.rodata._ZTIN5boost6detail11thread_dataI4TaskEE[_ZTIN5boost6detail11thread_dataI4TaskEE]+0x10): undefined reference to `typeinfo for boost::detail::thread_data_base'
I have a game server implemented in Java, however, I am migrating to C++.
I am trying to implement a server to my game. I am facing a problem when I try to detach a thread in the Client class. This thread would be responsible to listen to the client socket while the client is connect. I tried different strategies, however, I would like to keep it optimized and simple as possible. I believe the problem is related to the form that I am declaring the socket.
For the answer, rather than just pointing the problem, would be nice to check one example that fits with my structure. Moreover, I am open to opinions to improve my structure and performance of the server.
In the main, after accepting a new connection I create a new Client, and move the socket to it.
using boost::asio::ip::tcp;
void server(boost::asio::io_service&, tcp::endpoint&);
int main(int argc, char* argv[]) {
try {
boost::asio::io_service io_service;
tcp::endpoint end_point(tcp::v6(), 9990);
server(io_service, end_point);
} catch (std::exception& e) {
std::cerr << "Exception: " << e.what() << "\n";
}
return 0;
}
inline void server(boost::asio::io_service& io_service, tcp::endpoint& end_point) {
std::shared_ptr<NetworkManager> manager(new NetworkManager());
tcp::acceptor acceptor(io_service, end_point);
for (;;) {
std::cout << "Waiting for new connection." << std::endl;
acceptor.listen();
tcp::socket sock(io_service);
acceptor.accept(sock);
std::cout << "New connection accepted." << std::endl;
std::shared_ptr<Client> client = std::shared_ptr<Client>(new Client(std::move(sock), manager));
manager->add_client(client);
}
}
Client class
class Client {
private:
std::string id;
tcp::socket& sock;
std::shared_ptr<InterfaceManager> manager;
void session();
void send_start();
void update_transform(std::string);
std::vector<unsigned char> int_to_bytes(int);
public:
std::shared_ptr<Position> position;
std::shared_ptr<Rotation> rotation;
void send_to_client(std::string);
// Constructor and deconstructor
Client(tcp::socket, std::shared_ptr<InterfaceManager>);
virtual ~Client();
// Getters and Setters
std::string get_id() const;
};
In the constructor of the Client, store the manager which will contains all clients for broacasting, define UUID, position, rotation (for the transform), and detach() the thread. I tried to join() and it works for one client (because it does not continues in the main after creating the Client object).
Client::Client(tcp::socket socket, std::shared_ptr<InterfaceManager> i_manager) :
sock(socket) {
// For broadcast
this->manager = i_manager;
// Create UUID
boost::uuids::uuid uuid = boost::uuids::random_generator()();
id = to_string(uuid);
std::cout << "Client " << id << " connected." << std::endl;
// Define position and rotation
this->position = std::shared_ptr<Position>(new Position("0", "0", "0"));
this->rotation = std::shared_ptr<Rotation>(new Rotation("0", "0", "0", "0"));
// Start client thread
std::thread(&Client::session, this).detach();
}
The thread Client::session is this coded as bellow. This is a simple receive/reply thread (just for testing).
void Client::session() {
// Send start command
send_start();
try {
for (;;) {
char data[1024];
boost::system::error_code error;
sock.read_some(boost::asio::buffer(data), error);
if (error == boost::asio::error::eof) {
puts("Connection closed cleanly by peer");
break;
} else if (error) {
puts("Some other error");
throw boost::system::system_error(error);
}
std::string str(data);
std::cout << "Data received: " << data << std::endl;
//update_transform(str);
//manager->broadcast(id, str);
std::string s = "The received message is: " + str;
char* answer = const_cast<char*>(s.c_str());
size_t answer_length = std::strlen(answer);
boost::asio::write(sock, boost::asio::buffer(answer, answer_length));
}
} catch (std::exception& e) {
std::cerr << "Exception in thread: " << e.what() << "\n";
sock.close();
}
std::cout << "Client " << id << " closed its connection." << std::endl;
sock.close();
}
I am writing simple chat in Qt + Apache Thrift but right now I need to face a problem with connecting multiple clients. On first sight everything looks good and I cannot find where the problem is.
Here is my server main.cpp:
int main(int argc, char **argv)
{
int port = 9090;
::apache::thrift::stdcxx::shared_ptr<UsersStorageHandler> handler(new UsersStorageHandler());
::apache::thrift::stdcxx::shared_ptr<TProcessor> processor(new UsersStorageProcessor(handler));
::apache::thrift::stdcxx::shared_ptr<TServerTransport> serverTransport(new TServerSocket(port));
::apache::thrift::stdcxx::shared_ptr<TTransportFactory> transportFactory(new TBufferedTransportFactory());
::apache::thrift::stdcxx::shared_ptr<TProtocolFactory> protocolFactory(new TBinaryProtocolFactory());
TSimpleServer server(processor, serverTransport, transportFactory, protocolFactory);
std::cout << "Users server started..." << std::endl;
std::cout << std::endl;
std::cout << std::endl;
server.serve();
return 0;
}
Here is my server handler.h:
class UsersStorageHandler : virtual public UsersStorageIf
{
public:
UsersStorageHandler();
int32_t subscribeUser(const std::string& username);
void unsubscribeUser(const int32_t userID);
private:
Users users;
};
Here is my server handler.cpp:
UsersStorageHandler::UsersStorageHandler()
{
srand(time(NULL));
}
int32_t UsersStorageHandler::subscribeUser(const std::string &username)
{
++idGenerator;
assert(username != "");
User user;
user.userId = idGenerator;
user.username = username;
user.colorR = (rand() % 255) + 0;
user.colorG = (rand() % 255) + 0;
user.colorB = (rand() % 255) + 0;
user.colorA = 0;
users[idGenerator] = user;
std::cout << "NEW USER CONNECTED" << std::endl;
std::cout << "==================" << std::endl;
std::cout << "Username:\t" << user.username << std::endl;
std::cout << "User ID:\t" << user.userId << std::endl;
std::cout << "User R:\t" << user.colorR << std::endl;
std::cout << "User G:\t" << user.colorG << std::endl;
std::cout << "User B:\t" << user.colorB << std::endl;
std::cout << "User A:\t" << user.colorA << std::endl;
std::cout << "==================" << std::endl;
std::cout << "CURRENT USERS COUNT:\t" << users.size() << std::endl;
std::cout << std::endl;
std::cout << std::endl;
/*
* SEND TO CLIENT INFO ABOUT NEW USER HERE
*/
return idGenerator;
}
void UsersStorageHandler::unsubscribeUser(const int32_t userID)
{
auto index = users.find(userID);
assert(index != users.end());
users.erase(index);
std::cout << "USER DISCONNECTED" << std::endl;
std::cout << "=================" << std::endl;
std::cout << "USER WITH ID " << userID << " ERASED" << std::endl;
std::cout << "USERS COUNT:\t" << users.size() << std::endl;
std::cout << std::endl;
std::cout << std::endl;
/*
* SEND TO CLIENT INFO ABOUT NEW USER HERE
*/
}
And right here is a method for connect to the server in client app:
void MainWindow::connectToServers(const std::string &ip, const uint32_t &port, const std::string &nick)
{
m_usersServerIP = ip;
m_usersServerPort = port;
try
{
::apache::thrift::stdcxx::shared_ptr<TTransport> socket(new TSocket(m_usersServerIP, m_usersServerPort));
::apache::thrift::stdcxx::shared_ptr<TTransport> transport(new TBufferedTransport(socket));
::apache::thrift::stdcxx::shared_ptr<TProtocol> protocol(new TBinaryProtocol(transport));
m_usersServerClient = std::make_shared<UsersStorageClient>(protocol);
transport->open();
m_clientID = m_usersServerClient.get()->subscribeUser(nick);
QMessageBox::information(this, "Connected",
"You are connected "
"with users server");
createAndRegisterUsersServerReactor();
activateChatScreen();
}
catch (const std::exception &e)
{
qDebug() << e.what();
}
qDebug() << "ID FROM SERVER:\t" << m_clientID;
}
As far as I checked right now it is working like this: Created two instances of client app. In one instance fill nickname, ip, port and clicked connect (connectToServers method). Client connected. In another instance done the same but after clicked connected ... nothing happens. App freezes at this line:
m_clientID = m_usersServerClient.get()->subscribeUser(nick);
After closing first client, second one connects to the server.
Sincerelly i m not so expert with c++ RAII features. I never used before. Anyway i m begining to study about it. Compiling a module i have the following error :
In file included from /usr/include/c++/6/memory:81:0,
from ./java/./rocksjni/compaction_filter_factory_jnicallback.h:13,
from java/rocksjni/compaction_filter_factory_jnicallback.cc:9:
/usr/include/c++/6/bits/unique_ptr.h: In instantiation of ‘void std::unique_ptr<_Tp [], _Dp>::reset(_Up) [with _Up = char*; <template-parameter-2-2> = void; _Tp = const char; _Dp = std::default_delete<const char []>]’:
/usr/include/c++/6/bits/unique_ptr.h:539:9: required from ‘typename std::enable_if<std::__and_<std::__and_<std::is_array<_Up>, std::is_same<typename std::unique_ptr<_Tp [], _Dp>::_Pointer::type, _Tp*>, std::is_same<typename std::unique_ptr<_Up, _Ep>::pointer, typename std::unique_ptr<_Up, _Ep>::element_type*>, std::is_convertible<typename std::unique_ptr<_Up, _Ep>::element_type (*)[], _Tp (*)[]>, std::__or_<std::__and_<std::is_reference<_Dp>, std::is_same<_T2, _U2> >, std::__and_<std::__not_<std::is_reference<_Dp> >, std::is_convertible<_Ep, _Dp> > > >, std::is_assignable<_T2&, _U2&&> >::value, std::unique_ptr<_Tp [], _Dp>&>::type std::unique_ptr<_Tp [], _Dp>::operator=(std::unique_ptr<_Up, _Ep>&&) [with _Up = char []; _Ep = std::default_delete<char []>; _Tp = const char; _Dp = std::default_delete<const char []>; typename std::enable_if<std::__and_<std::__and_<std::is_array<_Up>, std::is_same<typename std::unique_ptr<_Tp [], _Dp>::_Pointer::type, _Tp*>, std::is_same<typename std::unique_ptr<_Up, _Ep>::pointer, typename std::unique_ptr<_Up, _Ep>::element_type*>, std::is_convertible<typename std::unique_ptr<_Up, _Ep>::element_type (*)[], _Tp (*)[]>, std::__or_<std::__and_<std::is_reference<_Dp>, std::is_same<_T2, _U2> >, std::__and_<std::__not_<std::is_reference<_Dp> >, std::is_convertible<_Ep, _Dp> > > >, std::is_assignable<_T2&, _U2&&> >::value, std::unique_ptr<_Tp [], _Dp>&>::type = std::unique_ptr<const char []>&]’
java/rocksjni/compaction_filter_factory_jnicallback.cc:33:58: required from here
/usr/include/c++/6/bits/unique_ptr.h:614:6: error: no matching function for call to ‘swap(const char*&, char*&)’
swap(std::get<0>(_M_t), __p);
~~~~^~~~~~~~~~~~~~~~~~~~~~~~
In file included from /usr/include/c++/6/bits/stl_pair.h:59:0,
from /usr/include/c++/6/bits/stl_algobase.h:64,
from /usr/include/c++/6/memory:62,
from ./java/./rocksjni/compaction_filter_factory_jnicallback.h:13,
from java/rocksjni/compaction_filter_factory_jnicallback.cc:9:
/usr/include/c++/6/bits/move.h:179:5: note: candidate: template<class _Tp> typename std::enable_if<std::__and_<std::is_move_constructible<_Tp>, std::is_move_assignable<_Tp> >::value>::type std::swap(_Tp&, _Tp&)
swap(_Tp& __a, _Tp& __b)
^~~~
/usr/include/c++/6/bits/move.h:179:5: note: template argument deduction/substitution failed:
In file included from /usr/include/c++/6/memory:81:0,
from ./java/./rocksjni/compaction_filter_factory_jnicallback.h:13,
from java/rocksjni/compaction_filter_factory_jnicallback.cc:9:
/usr/include/c++/6/bits/unique_ptr.h:614:6: note: deduced conflicting types for parameter ‘_Tp’ (‘const char*’ and ‘char*’)
swap(std::get<0>(_M_t), __p);
~~~~^~~~~~~~~~~~~~~~~~~~~~~~
In file included from /usr/include/c++/6/bits/stl_pair.h:59:0,
from /usr/include/c++/6/bits/stl_algobase.h:64,
from /usr/include/c++/6/memory:62,
from ./java/./rocksjni/compaction_filter_factory_jnicallback.h:13,
from java/rocksjni/compaction_filter_factory_jnicallback.cc:9:
/usr/include/c++/6/bits/move.h:202:5: note: candidate: template<class _Tp, long unsigned int _Nm> typename std::enable_if<std::__is_swappable<_Tp>::value>::type std::swap(_Tp (&)[_Nm], _Tp (&)[_Nm])
swap(_Tp (&__a)[_Nm], _Tp (&__b)[_Nm])
^~~~
/usr/include/c++/6/bits/move.h:202:5: note: template argument deduction/substitution failed:
In file included from /usr/include/c++/6/memory:81:0,
from ./java/./rocksjni/compaction_filter_factory_jnicallback.h:13,
from java/rocksjni/compaction_filter_factory_jnicallback.cc:9:
/usr/include/c++/6/bits/unique_ptr.h:614:6: note: mismatched types ‘_Tp [_Nm]’ and ‘std::__tuple_element_t<0ul, std::tuple<const char*, std::default_delete<const char []> > > {aka const char*}’
swap(std::get<0>(_M_t), __p);
~~~~^~~~~~~~~~~~~~~~~~~~~~~~
In file included from /usr/include/c++/6/bits/stl_algobase.h:64:0,
from /usr/include/c++/6/memory:62,
from ./java/./rocksjni/compaction_filter_factory_jnicallback.h:13,
from java/rocksjni/compaction_filter_factory_jnicallback.cc:9:
/usr/include/c++/6/bits/stl_pair.h:471:5: note: candidate: template<class _T1, class _T2> void std::swap(std::pair<_T1, _T2>&, std::pair<_T1, _T2>&)
swap(pair<_T1, _T2>& __x, pair<_T1, _T2>& __y)
^~~~
/usr/include/c++/6/bits/stl_pair.h:471:5: note: template argument deduction/substitution failed:
In file included from /usr/include/c++/6/memory:81:0,
from ./java/./rocksjni/compaction_filter_factory_jnicallback.h:13,
from java/rocksjni/compaction_filter_factory_jnicallback.cc:9:
/usr/include/c++/6/bits/unique_ptr.h:614:6: note: mismatched types ‘std::pair<_T1, _T2>’ and ‘std::__tuple_element_t<0ul, std::tuple<const char*, std::default_delete<const char []> > > {aka const char*}’
swap(std::get<0>(_M_t), __p);
~~~~^~~~~~~~~~~~~~~~~~~~~~~~
In file included from /usr/include/c++/6/string:52:0,
from /usr/include/c++/6/stdexcept:39,
from /usr/include/c++/6/array:39,
from /usr/include/c++/6/tuple:39,
from /usr/include/c++/6/functional:55,
from /usr/include/c++/6/memory:79,
from ./java/./rocksjni/compaction_filter_factory_jnicallback.h:13,
from java/rocksjni/compaction_filter_factory_jnicallback.cc:9:
/usr/include/c++/6/bits/basic_string.h:5287:5: note: candidate: template<class _CharT, class _Traits, class _Alloc> void std::swap(std::__cxx11::basic_string<_CharT, _Traits, _Alloc>&, std::__cxx11::basic_string<_CharT, _Traits, _Alloc>&)
swap(basic_string<_CharT, _Traits, _Alloc>& __lhs,
^~~~
/usr/include/c++/6/bits/basic_string.h:5287:5: note: template argument deduction/substitution failed:
In file included from /usr/include/c++/6/memory:81:0,
from ./java/./rocksjni/compaction_filter_factory_jnicallback.h:13,
from java/rocksjni/compaction_filter_factory_jnicallback.cc:9:
/usr/include/c++/6/bits/unique_ptr.h:614:6: note: mismatched types ‘std::__cxx11::basic_string<_CharT, _Traits, _Alloc>’ and ‘std::__tuple_element_t<0ul, std::tuple<const char*, std::default_delete<const char []> > > {aka const char*}’
swap(std::get<0>(_M_t), __p);
~~~~^~~~~~~~~~~~~~~~~~~~~~~~
In file included from /usr/include/c++/6/tuple:39:0,
from /usr/include/c++/6/functional:55,
from /usr/include/c++/6/memory:79,
from ./java/./rocksjni/compaction_filter_factory_jnicallback.h:13,
from java/rocksjni/compaction_filter_factory_jnicallback.cc:9:
/usr/include/c++/6/array:275:5: note: candidate: template<class _Tp, long unsigned int _Nm> void std::swap(std::array<_Tp, _Nm>&, std::array<_Tp, _Nm>&)
swap(array<_Tp, _Nm>& __one, array<_Tp, _Nm>& __two)
^~~~
/usr/include/c++/6/array:275:5: note: template argument deduction/substitution failed:
In file included from /usr/include/c++/6/memory:81:0,
from ./java/./rocksjni/compaction_filter_factory_jnicallback.h:13,
from java/rocksjni/compaction_filter_factory_jnicallback.cc:9:
/usr/include/c++/6/bits/unique_ptr.h:614:6: note: mismatched types ‘std::array<_Tp, _Nm>’ and ‘std::__tuple_element_t<0ul, std::tuple<const char*, std::default_delete<const char []> > > {aka const char*}’
swap(std::get<0>(_M_t), __p);
~~~~^~~~~~~~~~~~~~~~~~~~~~~~
In file included from /usr/include/c++/6/functional:55:0,
from /usr/include/c++/6/memory:79,
from ./java/./rocksjni/compaction_filter_factory_jnicallback.h:13,
from java/rocksjni/compaction_filter_factory_jnicallback.cc:9:
/usr/include/c++/6/tuple:1546:5: note: candidate: template<class ... _Elements> void std::swap(std::tuple<_Elements ...>&, std::tuple<_Elements ...>&)
swap(tuple<_Elements...>& __x, tuple<_Elements...>& __y)
^~~~
/usr/include/c++/6/tuple:1546:5: note: template argument deduction/substitution failed:
In file included from /usr/include/c++/6/memory:81:0,
from ./java/./rocksjni/compaction_filter_factory_jnicallback.h:13,
from java/rocksjni/compaction_filter_factory_jnicallback.cc:9:
/usr/include/c++/6/bits/unique_ptr.h:614:6: note: mismatched types ‘std::tuple<_Elements ...>’ and ‘std::__tuple_element_t<0ul, std::tuple<const char*, std::default_delete<const char []> > > {aka const char*}’
swap(std::get<0>(_M_t), __p);
~~~~^~~~~~~~~~~~~~~~~~~~~~~~
In file included from /usr/include/c++/6/memory:79:0,
from ./java/./rocksjni/compaction_filter_factory_jnicallback.h:13,
from java/rocksjni/compaction_filter_factory_jnicallback.cc:9:
/usr/include/c++/6/functional:2238:5: note: candidate: template<class _Res, class ... _Args> void std::swap(std::function<_Res(_ArgTypes ...)>&, std::function<_Res(_ArgTypes ...)>&)
swap(function<_Res(_Args...)>& __x, function<_Res(_Args...)>& __y)
^~~~
/usr/include/c++/6/functional:2238:5: note: template argument deduction/substitution failed:
In file included from /usr/include/c++/6/memory:81:0,
from ./java/./rocksjni/compaction_filter_factory_jnicallback.h:13,
from java/rocksjni/compaction_filter_factory_jnicallback.cc:9:
/usr/include/c++/6/bits/unique_ptr.h:614:6: note: mismatched types ‘std::function<_Res(_ArgTypes ...)>’ and ‘std::__tuple_element_t<0ul, std::tuple<const char*, std::default_delete<const char []> > > {aka const char*}’
swap(std::get<0>(_M_t), __p);
~~~~^~~~~~~~~~~~~~~~~~~~~~~~
In file included from /usr/include/c++/6/memory:81:0,
from ./java/./rocksjni/comparatorjnicallback.h:13,
from java/rocksjni/comparatorjnicallback.cc:9:
/usr/include/c++/6/bits/unique_ptr.h: In instantiation of ‘void std::unique_ptr<_Tp [], _Dp>::reset(_Up) [with _Up = char*; <template-parameter-2-2> = void; _Tp = const char; _Dp = std::default_delete<const char []>]’:
/usr/include/c++/6/bits/unique_ptr.h:539:9: required from ‘typename std::enable_if<std::__and_<std::__and_<std::is_array<_Up>, std::is_same<typename std::unique_ptr<_Tp [], _Dp>::_Pointer::type, _Tp*>, std::is_same<typename std::unique_ptr<_Up, _Ep>::pointer, typename std::unique_ptr<_Up, _Ep>::element_type*>, std::is_convertible<typename std::unique_ptr<_Up, _Ep>::element_type (*)[], _Tp (*)[]>, std::__or_<std::__and_<std::is_reference<_Dp>, std::is_same<_T2, _U2> >, std::__and_<std::__not_<std::is_reference<_Dp> >, std::is_convertible<_Ep, _Dp> > > >, std::is_assignable<_T2&, _U2&&> >::value, std::unique_ptr<_Tp [], _Dp>&>::type std::unique_ptr<_Tp [], _Dp>::operator=(std::unique_ptr<_Up, _Ep>&&) [with _Up = char []; _Ep = std::default_delete<char []>; _Tp = const char; _Dp = std::default_delete<const char []>; typename std::enable_if<std::__and_<std::__and_<std::is_array<_Up>, std::is_same<typename std::unique_ptr<_Tp [], _Dp>::_Pointer::type, _Tp*>, std::is_same<typename std::unique_ptr<_Up, _Ep>::pointer, typename std::unique_ptr<_Up, _Ep>::element_type*>, std::is_convertible<typename std::unique_ptr<_Up, _Ep>::element_type (*)[], _Tp (*)[]>, std::__or_<std::__and_<std::is_reference<_Dp>, std::is_same<_T2, _U2> >, std::__and_<std::__not_<std::is_reference<_Dp> >, std::is_convertible<_Ep, _Dp> > > >, std::is_assignable<_T2&, _U2&&> >::value, std::unique_ptr<_Tp [], _Dp>&>::type = std::unique_ptr<const char []>&]’
java/rocksjni/comparatorjnicallback.cc:34:21: required from here
/usr/include/c++/6/bits/unique_ptr.h:614:6: error: no matching function for call to ‘swap(const char*&, char*&)’
swap(std::get<0>(_M_t), __p);
~~~~^~~~~~~~~~~~~~~~~~~~~~~~
In file included from /usr/include/c++/6/bits/stl_pair.h:59:0,
from /usr/include/c++/6/bits/stl_algobase.h:64,
from /usr/include/c++/6/memory:62,
from ./java/./rocksjni/comparatorjnicallback.h:13,
from java/rocksjni/comparatorjnicallback.cc:9:
/usr/include/c++/6/bits/move.h:179:5: note: candidate: template<class _Tp> typename std::enable_if<std::__and_<std::is_move_constructible<_Tp>, std::is_move_assignable<_Tp> >::value>::type std::swap(_Tp&, _Tp&)
swap(_Tp& __a, _Tp& __b)
^~~~
/usr/include/c++/6/bits/move.h:179:5: note: template argument deduction/substitution failed:
In file included from /usr/include/c++/6/memory:81:0,
from ./java/./rocksjni/comparatorjnicallback.h:13,
from java/rocksjni/comparatorjnicallback.cc:9:
/usr/include/c++/6/bits/unique_ptr.h:614:6: note: deduced conflicting types for parameter ‘_Tp’ (‘const char*’ and ‘char*’)
swap(std::get<0>(_M_t), __p);
~~~~^~~~~~~~~~~~~~~~~~~~~~~~
In file included from /usr/include/c++/6/bits/stl_pair.h:59:0,
from /usr/include/c++/6/bits/stl_algobase.h:64,
from /usr/include/c++/6/memory:62,
from ./java/./rocksjni/comparatorjnicallback.h:13,
from java/rocksjni/comparatorjnicallback.cc:9:
/usr/include/c++/6/bits/move.h:202:5: note: candidate: template<class _Tp, long unsigned int _Nm> typename std::enable_if<std::__is_swappable<_Tp>::value>::type std::swap(_Tp (&)[_Nm], _Tp (&)[_Nm])
swap(_Tp (&__a)[_Nm], _Tp (&__b)[_Nm])
^~~~
/usr/include/c++/6/bits/move.h:202:5: note: template argument deduction/substitution failed:
In file included from /usr/include/c++/6/memory:81:0,
from ./java/./rocksjni/comparatorjnicallback.h:13,
from java/rocksjni/comparatorjnicallback.cc:9:
/usr/include/c++/6/bits/unique_ptr.h:614:6: note: mismatched types ‘_Tp [_Nm]’ and ‘std::__tuple_element_t<0ul, std::tuple<const char*, std::default_delete<const char []> > > {aka const char*}’
swap(std::get<0>(_M_t), __p);
~~~~^~~~~~~~~~~~~~~~~~~~~~~~
In file included from /usr/include/c++/6/bits/stl_algobase.h:64:0,
from /usr/include/c++/6/memory:62,
from ./java/./rocksjni/comparatorjnicallback.h:13,
from java/rocksjni/comparatorjnicallback.cc:9:
/usr/include/c++/6/bits/stl_pair.h:471:5: note: candidate: template<class _T1, class _T2> void std::swap(std::pair<_T1, _T2>&, std::pair<_T1, _T2>&)
swap(pair<_T1, _T2>& __x, pair<_T1, _T2>& __y)
^~~~
/usr/include/c++/6/bits/stl_pair.h:471:5: note: template argument deduction/substitution failed:
In file included from /usr/include/c++/6/memory:81:0,
from ./java/./rocksjni/comparatorjnicallback.h:13,
from java/rocksjni/comparatorjnicallback.cc:9:
/usr/include/c++/6/bits/unique_ptr.h:614:6: note: mismatched types ‘std::pair<_T1, _T2>’ and ‘std::__tuple_element_t<0ul, std::tuple<const char*, std::default_delete<const char []> > > {aka const char*}’
swap(std::get<0>(_M_t), __p);
~~~~^~~~~~~~~~~~~~~~~~~~~~~~
In file included from /usr/include/c++/6/string:52:0,
from /usr/include/c++/6/stdexcept:39,
from /usr/include/c++/6/array:39,
from /usr/include/c++/6/tuple:39,
from /usr/include/c++/6/functional:55,
from /usr/include/c++/6/memory:79,
from ./java/./rocksjni/comparatorjnicallback.h:13,
from java/rocksjni/comparatorjnicallback.cc:9:
/usr/include/c++/6/bits/basic_string.h:5287:5: note: candidate: template<class _CharT, class _Traits, class _Alloc> void std::swap(std::__cxx11::basic_string<_CharT, _Traits, _Alloc>&, std::__cxx11::basic_string<_CharT, _Traits, _Alloc>&)
swap(basic_string<_CharT, _Traits, _Alloc>& __lhs,
^~~~
/usr/include/c++/6/bits/basic_string.h:5287:5: note: template argument deduction/substitution failed:
In file included from /usr/include/c++/6/memory:81:0,
from ./java/./rocksjni/comparatorjnicallback.h:13,
from java/rocksjni/comparatorjnicallback.cc:9:
/usr/include/c++/6/bits/unique_ptr.h:614:6: note: mismatched types ‘std::__cxx11::basic_string<_CharT, _Traits, _Alloc>’ and ‘std::__tuple_element_t<0ul, std::tuple<const char*, std::default_delete<const char []> > > {aka const char*}’
swap(std::get<0>(_M_t), __p);
~~~~^~~~~~~~~~~~~~~~~~~~~~~~
In file included from /usr/include/c++/6/tuple:39:0,
from /usr/include/c++/6/functional:55,
from /usr/include/c++/6/memory:79,
from ./java/./rocksjni/comparatorjnicallback.h:13,
from java/rocksjni/comparatorjnicallback.cc:9:
/usr/include/c++/6/array:275:5: note: candidate: template<class _Tp, long unsigned int _Nm> void std::swap(std::array<_Tp, _Nm>&, std::array<_Tp, _Nm>&)
swap(array<_Tp, _Nm>& __one, array<_Tp, _Nm>& __two)
^~~~
/usr/include/c++/6/array:275:5: note: template argument deduction/substitution failed:
In file included from /usr/include/c++/6/memory:81:0,
from ./java/./rocksjni/comparatorjnicallback.h:13,
from java/rocksjni/comparatorjnicallback.cc:9:
/usr/include/c++/6/bits/unique_ptr.h:614:6: note: mismatched types ‘std::array<_Tp, _Nm>’ and ‘std::__tuple_element_t<0ul, std::tuple<const char*, std::default_delete<const char []> > > {aka const char*}’
swap(std::get<0>(_M_t), __p);
~~~~^~~~~~~~~~~~~~~~~~~~~~~~
In file included from /usr/include/c++/6/functional:55:0,
from /usr/include/c++/6/memory:79,
from ./java/./rocksjni/comparatorjnicallback.h:13,
from java/rocksjni/comparatorjnicallback.cc:9:
/usr/include/c++/6/tuple:1546:5: note: candidate: template<class ... _Elements> void std::swap(std::tuple<_Elements ...>&, std::tuple<_Elements ...>&)
swap(tuple<_Elements...>& __x, tuple<_Elements...>& __y)
^~~~
/usr/include/c++/6/tuple:1546:5: note: template argument deduction/substitution failed:
In file included from /usr/include/c++/6/memory:81:0,
from ./java/./rocksjni/comparatorjnicallback.h:13,
from java/rocksjni/comparatorjnicallback.cc:9:
/usr/include/c++/6/bits/unique_ptr.h:614:6: note: mismatched types ‘std::tuple<_Elements ...>’ and ‘std::__tuple_element_t<0ul, std::tuple<const char*, std::default_delete<const char []> > > {aka const char*}’
swap(std::get<0>(_M_t), __p);
~~~~^~~~~~~~~~~~~~~~~~~~~~~~
In file included from /usr/include/c++/6/memory:79:0,
from ./java/./rocksjni/comparatorjnicallback.h:13,
from java/rocksjni/comparatorjnicallback.cc:9:
/usr/include/c++/6/functional:2238:5: note: candidate: template<class _Res, class ... _Args> void std::swap(std::function<_Res(_ArgTypes ...)>&, std::function<_Res(_ArgTypes ...)>&)
swap(function<_Res(_Args...)>& __x, function<_Res(_Args...)>& __y)
^~~~
/usr/include/c++/6/functional:2238:5: note: template argument deduction/substitution failed:
In file included from /usr/include/c++/6/memory:81:0,
from ./java/./rocksjni/comparatorjnicallback.h:13,
from java/rocksjni/comparatorjnicallback.cc:9:
/usr/include/c++/6/bits/unique_ptr.h:614:6: note: mismatched types ‘std::function<_Res(_ArgTypes ...)>’ and ‘std::__tuple_element_t<0ul, std::tuple<const char*, std::default_delete<const char []> > > {aka const char*}’
swap(std::get<0>(_M_t), __p);
I m not sure to understand this stack trace but it seams there is a mismatch in the unique_ptr . Maybe const char* and char*.
the class where there is the bug is :
CompactionFilterFactoryJniCallback::CompactionFilterFactoryJniCallback(
JNIEnv* env, jobject jcompaction_filter_factory)
: JniCallback(env, jcompaction_filter_factory) {
// Note: The name of a CompactionFilterFactory will not change during
// it's lifetime, so we cache it in a global var
jmethodID jname_method_id =
AbstractCompactionFilterFactoryJni::getNameMethodId(env);
if(jname_method_id == nullptr) {
// exception thrown: NoSuchMethodException or OutOfMemoryError
return;
}
jstring jname =
(jstring)env->CallObjectMethod(m_jcallback_obj, jname_method_id);
if(env->ExceptionCheck()) {
// exception thrown
return;
}
jboolean has_exception = JNI_FALSE;
m_name = JniUtil::copyString(env, jname, &has_exception); // also releases jname
if (has_exception == JNI_TRUE) {
// exception thrown
return;
}
m_jcreate_compaction_filter_methodid =
AbstractCompactionFilterFactoryJni::getCreateCompactionFilterMethodId(env);
if(m_jcreate_compaction_filter_methodid == nullptr) {
// exception thrown: NoSuchMethodException or OutOfMemoryError
return;
}
}
const char* CompactionFilterFactoryJniCallback::Name() const {
return m_name.get();
}
std::unique_ptr<CompactionFilter> CompactionFilterFactoryJniCallback::CreateCompactionFilter(
const CompactionFilter::Context& context) {
jboolean attached_thread = JNI_FALSE;
JNIEnv* env = getJniEnv(&attached_thread);
assert(env != nullptr);
jlong addr_compaction_filter = env->CallLongMethod(m_jcallback_obj,
m_jcreate_compaction_filter_methodid,
static_cast<jboolean>(context.is_full_compaction),
static_cast<jboolean>(context.is_manual_compaction));
if(env->ExceptionCheck()) {
// exception thrown from CallLongMethod
env->ExceptionDescribe(); // print out exception to stderr
releaseJniEnv(attached_thread);
return nullptr;
}
auto* const cff = reinterpret_cast<CompactionFilter*>(addr_compaction_filter);
releaseJniEnv(attached_thread);
return std::unique_ptr<CompactionFilter>(cff);
}
It is not clear how to read this stack trace for identifying the problem. I would appreciate to receive a little suggestion for understand how fix the problem and read the stack trace.