question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
73,272,037
73,272,099
How do you find out the cause of rare crashes that are caused by things that are not caught by try catch (access violation, divide by zero, etc.)?
I am a .NET programmer who is starting to dabble into C++. In C# I would put the root function in a try catch, this way I would catch all exceptions, save the stack trace, and this way I would know what caused the exception, significantly reducing the time spent debugging. But in C++ some stuff(access violation, divide by zero, etc.) are not caught by try catch. How do you deal with them, how do you know which line of code caused the error? For example let's assume we have a program that has 1 million lines of code. It's running 24/7, has no user-interaction. Once in a month it crashes because of something that is not caught by try catch. How do you find out which line of code caused the crash? Environment: Windows 10, MSVC.
C++ is meant to be a high performance language and checks are expensive. You can't run at C++ speeds and at the same time have all sorts of checks. It is by design. Running .Net this way is akin to running C++ in debug mode with sanitizers on. So if you want to run your application with all the information you can, turn on debug mode in your cmake build and add sanitizers, at least undefined and address sanitizers. For Windows/MSVC it seems that address sanitizers were just added in 2021. You can check the announcement here: https://devblogs.microsoft.com/cppblog/addresssanitizer-asan-for-windows-with-msvc/ For Windows/mingw or Linux/* you can use Gcc and Clang's builtin sanitizers that have largely the same usage/syntax. To set your build to debug mode: cd <builddir> cmake -DCMAKE_BUILD_TYPE=debug <sourcedir> To enable sanitizers, add this to your compiler command line: -fsanitize=address,undefined One way to do that is to add it to your cmake build so altogether it becomes: cmake -DCMAKE_BUILD_TYPE=debug \ -DCMAKE_CXX_FLAGS_DEBUG_INIT="-fsanitize=address,undefined" \ <sourcedir> Then run your application binary normally as you do. When an issue is found a meaningful message will be printed along with a very informative stack trace. Alternatively you can set so the sanitizer breaks inside the debugger (gdb) so you can inspect it live but that only works with the undefined sanitizer. To do so, replace -fsanitize=address,undefined with -fsanitize-undefined-trap-on-error -fsanitize-trap=undefined -fsanitize=address For example, this code has a clear problem: void doit( int* p ) { *p = 10; } int main() { int* ptr = nullptr; doit(ptr); } Compile it in the optimized way and you get: $ g++ -O3 test.cpp -o test $ ./test Segmentation fault (core dumped) Not very informative. You can try to run it inside the debugger but no symbols are there to see. $ g++ -O3 test.cpp -o test $ gdb ./test GNU gdb (Ubuntu 9.2-0ubuntu1~20.04.1) 9.2 ... Reading symbols from ./test... (No debugging symbols found in ./test) (gdb) r Starting program: /tmp/test Program received signal SIGSEGV, Segmentation fault. 0x0000555555555044 in main () (gdb) That's useless so we can turn on debug symbols with $ g++ -g3 test.cpp -o test $ gdb ./test GNU gdb (Ubuntu 9.2-0ubuntu1~20.04.1) 9.2 Copyright (C) 2020 Free Software Foundation, Inc. ... Reading symbols from ./test... (gdb) r Starting program: /tmp/test [Thread debugging using libthread_db enabled] Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1". test.cpp:4:5: runtime error: store to null pointer of type 'int' Program received signal SIGSEGV, Segmentation fault. 0x0000555555555259 in doit (p=0x0) at test.cpp:4 4 *p = 10; Then you can inspect inside: (gdb) p p $1 = (int *) 0x0 Now, turn on sanitizers to get even more messages without the debugger: $ g++ -O0 -g3 test.cpp -fsanitize=address,undefined -o test $ ./test test.cpp:4:5: runtime error: store to null pointer of type 'int' AddressSanitizer:DEADLYSIGNAL ================================================================= ==931717==ERROR: AddressSanitizer: SEGV on unknown address 0x000000000000 (pc 0x563b7b66c259 bp 0x7fffd167c240 sp 0x7fffd167c230 T0) ==931717==The signal is caused by a WRITE memory access. ==931717==Hint: address points to the zero page. #0 0x563b7b66c258 in doit(int*) /tmp/test.cpp:4 #1 0x563b7b66c281 in main /tmp/test.cpp:9 #2 0x7f36164a9082 in __libc_start_main ../csu/libc-start.c:308 #3 0x563b7b66c12d in _start (/tmp/test+0x112d) AddressSanitizer can not provide additional info. SUMMARY: AddressSanitizer: SEGV /tmp/test.cpp:4 in doit(int*) ==931717==ABORTING That is much better!
73,272,190
73,272,408
C++ convert iterator from map to object pointer
Trying to find an object in a map, and set a member class pointer variable. # Animations.h #ifndef _ANIMATIONS_H #define _ANIMATIONS_H #include <map> #include "Animation.h" using namespace std; class Animations { public: Animations(); void add(Animation* animation, string name); void play(string name); Animation* animation; map<string, Animation*> animations; }; #endif # Animations.cpp ... void Animations::play(string name) { std::map<string, Animation*>::iterator itr = animations.find(name); if (itr != animations.end()) { animation = itr->second; } } I've seen lots of examples with itr->second in couts and printing, which I've tested, works fine. However I need to convert it to an Animation * somehow, but don't know how. When I use the variable from above, it compiles, but the data is all messed up (frame should be 0 and instead is some huge int) so probably wrong memory address. I did verify the frame of the original Animation object is 0, and a pointer to it is 0 too before adding it to the map. The closest I've come is this &(*itr); via https://stackoverflow.com/a/2160319/1183537 and what I'm doing is close to c++ Find map value and key although I want to assign the variable, not just print it out, which are the examples I usually find on map#find like https://cplusplus.com/reference/map/map/find/ and https://www.guru99.com/cpp-map-stl.html Can anyone lend some help? I'm newish to C++, and rusty on C, but programming for 10+ years, so I should be able to handle this. edit: here's how i'm adding animations: # Animations.cpp void Animations::add(Animation* animation, string name) { animations[name] = animation; cout << "> Animations::add " << name << " frame: " << animation->frame << endl; } and here's how I'm testing the set animation pointer: # Animations.cpp void Animations::update() { cout << "> Animations::update" << endl; if (animation != NULL) { cout << "> Animations::update animation frame: " << animation->frame << " " << animation->width << "x" << animation->height << endl; animation->update(); } cout << "> Animations::update done" << endl; } here's where I was creating the Animations and calling animations.add: # Player.cpp ... void Player::initAnimations(ALLEGRO_BITMAP* sheet) { Animation spark(FPS, true, true); Animation explosion(FPS / 3, true, true); spark.add(sheet, 34, 0, 10, 8); spark.add(sheet, 45, 0, 7, 8); spark.add(sheet, 54, 0, 9, 8); animations.add(&spark, "spark"); animations.play("spark"); } I've tried not using pointers, from the comment suggestions. But I'm getting error error: no matching constructor for initialization of 'Animation' around the place where I do animation = itr->second; not sure if it needs to be itr.second instead, I think I tried both.
I switched to non pointers in the map # Animations.h map<string, Animation> animations; Animation* animation; while leaving the animation a pointer. Then thanks to @EtiennedMartel's comment I used &itr->second to set the Animation* animation pointer. The other thing I needed to do was to add a default Animation() constructor, which I originally didn't have, which was needed from the map/iterator. # Animations.cpp void Animations::play(string name) { std::map<string, Animation>::iterator itr = animations.find(name); if (itr != animations.end()) animation = &itr->second; }
73,272,505
73,272,547
Discrepancy in C++ constructor destructor execution order
I understand that the order of calling the destructor is in the reverse order of creation of the objects. However in the following code I don't understand why the destructor for C(1) and C(2) get called immediately after their constructor. Also what is the difference between statements: C(2) and C c3(3). The second one is an object initialized with value 3. What is the interpretation of C(2)? #include <iostream> class C { public: C(int i) { j = i; std::cout << "constructor called for "<<j << std::endl;; } ~C() { std::cout << "destructor called for "<<j<< std::endl;; } private: int j; }; int main() { C(1); C(2); C c3(3); C c4(4); } The output of the code is: constructor called for 1 destructor called for 1 constructor called for 2 destructor called for 2 constructor called for 3 constructor called for 4 destructor called for 4 destructor called for 3
C(1); is a statement containing an expression that creates a temporary of type C, constructed from the argument 1. The temporary is not named - there is no variable name, and no way to refer to that object after the statement finishes executing - so the temporary object's destructor runs immediately after the statement. That contrasts with C c3(3);, which is a variable definition for the variable named c3. It remains in scope until the end of the enclosing scope, which in this case is the function scope. Because of that, the c4 constructor and destructor run before c3's destructor.
73,272,889
73,273,317
Why visual c++ (latest) and gcc 12.1 accepted hiding this init capture for lambda, while clang 14.0.0 not? (c++20)
Case 1 int main() { int x = 100; auto lamb_var = [y = x](){ int y = 10; return y + 1; }; assert (lamb_var() == 11); return 0; } in https://godbolt.org/z/hPPParjnz Both MSVC and GCC accepted shadowing the init-capture, while Clang accused y redefinition on the compound statement and throwed compiler error. However, if we remove the init-capture and make a simple-capture, all compilers accept Shadowing: Case 2 int main() { int x = 100; auto lamb_var = [x](){ int x = 10; return x + 1; }; assert (lamb_var() == 11); return 0; } in https://godbolt.org/z/Gs4cadf5e A simple-capture (case 2) leads to the creation of an attribute in the lambda-associated class, so shadowing should be normal. From what I found,the expression "whose declarative region is the body of the lambda expression" of the quote below from cppreference could defend the implementation of CLANG ("redefinition"), but I'm not sure. A capture with an initializer acts as if it declares and explicitly captures a variable declared with type auto, whose declarative region is the body of the lambda expression (that is, it is not in scope within its initializer), except that: [...] Who is right in implementation (GCC and MSVC or Clang), and how to understand this citation of cppreference? Related questions Lambda capture and parameter with same name - who shadows the other? (clang vs gcc)
I think that clang is correct in rejecting snippet 1 and accepting snippet 2 because in the first case the non-static data member is named y while in the second case the non-static data member is unnamed. Case 1 Here we consider snippet 1: int main() { int x = 100; auto lamb_var = [y = x](){ //the data member is "named" y int y = 10; //error because we're defining y for second time return y + 1; }; assert (lamb_var() == 11); return 0; } Now, from expr.prim.lambda#capture-6: An init-capture without ellipsis behaves as if it declares and explicitly captures a variable of the form auto init-capture ; whose declarative region is the lambda-expression's compound-statement, except that: (emphasis mine) This seems to indicate that the non-static data member has a name which in your given example is y. Now, by writing int y = 10; we're providing a redefinition of the same named variable y in the same declarative region and hence the error. Note that we will get the same error(as expected due to the reason explained above), if we replace [y=x] with [x=x] and int y =10; with int x = 10; as shown below: int main() { int x = 100; auto lamb_var = [x = x](){ //data member "named" x int x = 10; //this will give same error return x + 1; }; assert (lamb_var() == 11); return 0; } Case 2 Here we consider the snippet 2: int main() { int x = 100; auto lamb_var = [x](){ //data member is unnamed int x = 10; //ok because we're defining an int variable with "name" x for the first time in this region return x + 1; }; assert (lamb_var() == 11); return 0; } Here from expr.prim.lambda#capture-10: For each entity captured by copy, an unnamed non-static data member is declared in the closure type. The declaration order of these members is unspecified.... (emphasis mine) In this case, the non-static data member is unnamed and so writing int x = 10; is not a redefinition error because we're definining a variable named x for the first time in this region.
73,273,084
73,273,145
How to dynamically allocate work to threads
I am trying to write code for finding if pairwise sums are even or not(among all possible pairs from 0 to 100000). I have written code using pthreads where the work allocation is done statically. Here is the code #include<iostream> #include<chrono> #include<iomanip> #include<pthread.h> using namespace std; #define MAX_THREAD 4 vector<long long> cnt(MAX_THREAD,0); long long n = 100000; int work_per_thread; void *count_array(void* arg) { int t = *((int*)arg); long long sum = 0; int counter = 0; for(int i = t*work_per_thread + 1; i <= (t+1)*work_per_thread; i++) for(int j = i-1; j >= 0; j--) { sum = i + j; if(sum%2 == 0) counter++; } cnt[t] = counter; cout<<"thread"<<t<<" finished work"<<endl; return NULL; } int main() { pthread_t threads[MAX_THREAD]; vector<int> arr; for(int i = 0; i < MAX_THREAD; i++) arr.push_back(i); long long total_count = 0; work_per_thread = n/MAX_THREAD; auto start = chrono::high_resolution_clock::now(); for (int i = 0; i < MAX_THREAD; i++) pthread_create(&threads[i], NULL, count_array, &arr[i]); for (int i = 0; i < MAX_THREAD; i++) pthread_join(threads[i], NULL); for (int i = 0; i < MAX_THREAD; i++) total_count += cnt[i]; cout << "count is " << total_count << endl; auto end = chrono::high_resolution_clock::now(); double time_taken = chrono::duration_cast<chrono::nanoseconds>(end - start).count(); time_taken *= 1e-9; cout << "Time taken by program is : " << fixed << time_taken << setprecision(9)<<" secs"<<endl; return 0; } Now I want to do the work allocation part dynamically. To be specific, let's say I have 5 threads. Initially I give the threads a certain range to work with, let's say thread1 works on all pairs from 0-1249, thread2 from 1250-2549 and so on. Now as soon as a thread completes its work I want to give it a new range to work on. This way no threads will be idle for most of the time, like was in the case of static allocation.
This is the classic usage of a thread pool. Typically you set up a synchronized queue that can be pushed and pulled by any number of threads. Then you start N threads, the "thread pool". These threads wait on a condition variable that locks a mutex. When you have work to do from the main thread, it pushes work into the queue (it can be as simple as a struct with a range) and then signals the condition variable, which will release one thread. See this answer: https://codereview.stackexchange.com/questions/221617/thread-pool-c-implementation
73,273,305
73,273,609
why the text of label didn't show the result initialized in custom class?
There is the complete process: Create a project, choose Base class: QWidget, including .h .cpp .ui [Add New...] -> create a [ C++ class] -> choose base class: [QWidget], but named myLabel. Open mylabel.h, change QWidget of including file and parent class to QLabel mylabel.h #ifndef MYLABEL_H #define MYLABEL_H #include <QLabel> class myLabel : public QLabel { Q_OBJECT public: explicit myLabel(QWidget *parent = nullptr); signals: }; #endif // MYLABEL_H Open mylabel.cpp, change the parent class into QLabel too, and set text content mylabel.cpp #include "mylabel.h" myLabel::myLabel(QWidget *parent) : QLabel{parent} { this->setText("test"); }   widget.h #ifndef WIDGET_H #define WIDGET_H #include <QWidget> QT_BEGIN_NAMESPACE namespace Ui { class Widget; } QT_END_NAMESPACE class Widget : public QWidget { Q_OBJECT public: Widget(QWidget *parent = nullptr); ~Widget(); private: Ui::Widget *ui; }; #endif // WIDGET_H   widget.cpp #include "widget.h" #include "ui_widget.h" Widget::Widget(QWidget *parent) : QWidget(parent) , ui(new Ui::Widget) { ui->setupUi(this); } Widget::~Widget() { delete ui; } Now i got a custom class, and create a label in the widget.ui add a widget, put the label in, choose widget and label, ctrl+L just like this Promote label to myLabel. label was promoted to myLabel Run. running result This isn't what i expect. So, why the text of label didn't change? or maybe something ignored? plz, even a keyword that can help me searching...
Check the code of setupUi method. When you use QT Designer to create your widget, each widget has some properties (like geometry, object name, initial text for label etc) which have to be initialized. This is done in setupUi. The code corresponding your case may look like: void setupUi() { label = new myLabel(widgetParent); // setText with test label->setObjectName(... label->setGeometry(... label->setAlignment(... label->setText(TEXT_FROM_DESIGNER); // <--- } The text test set by constructor of myLabel widget is overwritten by calling setText in setupUi method with text choosen in Designer. If you want to change some properties of created widgets it should be done after setupUi: Widget::Widget(QWidget *parent) : QWidget(parent) , ui(new Ui::Widget) { ui->setupUi(this); // change label's text }
73,273,696
73,273,846
Unable to read from external text file
I've got a dynamically allocated array of a struct type (let's call it structtype), and I was trying to read to it from an external text file. structtype looks something like this: { char itemName[15]; char status; int itemAmt; char tried; char desc[130]; int rating; } And the text file looks something like this: SomeName: y | 3 | Hello Hello | y | 9 in that exact format. I am trying to read from said text file using this code: void games::LoadFrom(){ // Loads games from the file into array (AllItems) ifstream file_in; structtype temparray[15] = {}; for (int i = 0; i < 15; ++i) // Empties out AllItems AllItems[i] = {}; file_in.open("items.txt"); int i = 0; // Counter if (file_in){ while (!file_in.eof() && i < 15){ // Checks if its the end of the file, or if its the max amount I can store file_in.get(temparray[i].itemName, 15, ':'); file_in.ignore(100, '|'); file_in >> temparray[i].status; file_in.ignore(100, '|'); AllItems[i].status = temparray[i].status; file_in >> temparray[i].itemAmt; file_in.ignore(100, '|'); AllItems[i].playerAmt = temparray[i].itemAmt; file_in.get(temparray[i].desc, 131, '|'); // All of this reads in a game from the file, and stores it in the AllItems array file_in.ignore(100, '|'); file_in >> temparray[i].tried; file_in.ignore(100, '|'); AllItems[i].tried = temparray[i].tried; file_in >> temparray[i].rating; file_in.ignore(100, '\n'); AllItems[i].rating = temparray[i].rating; ++i; file_in.get(temparray[i].itemName, 15, ':'); file_in.ignore(100, ':'); } cout << AllItems[0].itemAmt; } cout << AllItems[0].itemAmt; file_in.close(); } My problem is that it doesn't read anything in, and instead leaves everything in the struct object at its zero equivalent. Important To keep in mind: AllItems is a dynamically allocated array, and I was unable to read stuff to it directly, instead I made a separate statically allocated array called temparray, which is strictly for transferring info to AllItems. When the loop runs, it runs once, and then exits, even though the text file has about 10 items. How can I actually read items in?
Here's what your code should look like. I've ignored the AllItems and AllGames arrays, and just concentrated on temparray while (!file_in.eof() && i < 15){ // Checks if its the end of the file, or if its the max amount I can store file_in.getline(temparray[i].itemName, 15, ':'); file_in >> temparray[i].status; file_in.ignore(100, '|'); file_in >> temparray[i].itemAmt; file_in.ignore(100, '|'); file_in.getline(temparray[i].desc, 130, '|'); // All of this reads in a game from the file, and stores it in the AllItems array file_in >> temparray[i].tried; file_in.ignore(100, '|'); file_in >> temparray[i].rating; file_in.ignore(100, '\n'); ++i; } Main differences with your code - I've used getline not get so the terminating character (':' or '|') is read and discarded. I've only used ignore after a formatted extraction (i.e. after >>) when it is necessary to discard the trailing separator. When you are writing this kind of code you have to understand in detail what each reading function does, and how that effects the file format you have. It's not good enough to throw together a bunch of code that is roughly the same as your file format, it has to be exactly right. EDIT As pointed out in the comments below the above code has a problem which is how it handles end of file. It makes the common error of testing for eof before a read, not afterwards. Here's a version that tests correctly. while (i < 15 && file_in.getline(temparray[i].itemName, 15, ':') && file_in >> temparray[i].status && file_in.ignore(100, '|') && file_in >> temparray[i].itemAmt && file_in.ignore(100, '|') && file_in.getline(temparray[i].desc, 130, '|') && file_in >> temparray[i].tried && file_in.ignore(100, '|') && file_in >> temparray[i].rating && file_in.ignore(100, '\n')) { ++i; } In this version only if all reads succeed does the while loop get executed and i get incremented. A read could fail either because of end of file, or because of a format error. If you need to distinguish those two cases you need some more sophisticated code.
73,273,817
73,274,047
How to erase a string if it contains any character in a set [c++]
I am new to C++ and could not find a solution in any post for this. I have a vector of strings and I wish to erase a string from this vector if it contains any of these symbols: {'.', '%', '&','(',')', '!', '-', '{', '}'}. I am aware of find(), which only takes one character to search for; however, I want to go through each word in the string vector and erase them if they contain any of these characters. E.g. find('.') does not suffice. I have tried multiple routes such as creating a char vector of all these characters and looping through each one as a find() parameter. However, this logic is very flawed, as it will cause an abort trap if the vector only has one line with a '.' in it, or leaves some strings with the unwanted character inside. vector<std::string> lines = {"hello..","Hello...", "hi%", "world","World!"} vector<char> c = {'.', '%', '&','(',')', '!', '-', '{', '}'}; for (int i=0; i < lines.size(); i++){ for(int j=0; j < c.size(); j++){ if (lines.at(i).find(c.at(j)) != string::npos ){ lines.erase(lines.begin() + i); } } } I have also tried find_first_of() inside a loop of vector 'lines', which yields the same result as there above code. if (lines.at(i).find_first_of(".%&()!-{}") != string::npos ){ lines.erase(lines.begin() + i); Can someone please help me with this logic? EDIT: when I put in --i after erasing the line, instead nothing is displayed and I have an abort trap because it loops outside vector range.
There are two issues in your code, both 'inside' the inner for loop when a match is found. First, you keep checking the same vector element for a (further) match, even after you erase it; to fix this, add a break; statement inside the if block, to prevent further runs of that inner loop after a match has been found and the erase() call has been made. Second, when you do erase an element, you need to decrement the i index (which will be incremented before the start of the next outer loop), so that you aren't skipping the check for the element that i will index after the erasure. Here's a fixed version of your code: #include <iostream> #include <vector> #include <string> int main() { std::vector<std::string> lines = { "hello..", "Hello...", "hi%", "world", "World!" }; std::vector<char> c = { '.', '%', '&','(',')', '!', '-', '{', '}' }; for (size_t i = 0; i < lines.size(); i++) { for (size_t j = 0; j < c.size(); j++) { if (lines.at(i).find(c.at(j)) != std::string::npos) { lines.erase(lines.begin() + static_cast<ptrdiff_t>(i)); i--; // Decrement the i index to avoid skipping next string break; // Need to break out of inner loop as "i" is now wrong! } } } for (auto l : lines) { std::cout << l << std::endl; } return 0; } However, as pointed out in other answers, you can improve your code significantly by making more use of the functions offered by the Standard Library.
73,274,134
73,274,170
Why is the counter value not incrementing?
The counter does not increase at all so I want to know which part went wrong. #include <cstring> #include <iostream> using namespace std; int main(){ int total=0,na=0,ni=0;//use to count how much type of element is there string chem; getline(cin,chem); for(int i=0;i!='\0';i++){ if(chem[i]=='N'){ if(chem[i+1]=='i'){ ni++; }else{ na++; cout<<na<<endl; } } } na and total values are both 0 cout<<na<<endl; total=total + ni+na; cout<<total;
for(int i=0;i!='\0';i++){ is the same as for(int i=0; i; i++){ ('\0' is a char type with value 0). The conditional check means the loop body never runs.
73,274,152
73,274,360
Undefined reference while compiling (compiler flag problem)
I am working on a project where I use google protobuffers. I am currently stuck at the compilation of the program in the CLion IDE. Everytime I compile with WSL, the following errors occur: /usr/bin/ld: /mnt/c/Users/***/Documents/***/Protobuf_examples/data.pb.cc:146: undefined reference to `google::protobuf::internal::ArenaStringPtr::Set(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, google::protobuf::Arena*)' /usr/bin/ld: /mnt/c/Users/***/Documents/***/Protobuf_examples/data.pb.cc:154: undefined reference to `google::protobuf::internal::ArenaStringPtr::Set(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, google::protobuf::Arena*)' There are certain compiler flags needed for a successful compilation. Whenever I compile from a linux subsystem everything works with the following command: c++ main.cpp data.pb.h data.pb.cc -o proto -pthread -I/usr/local/include -pthread -L/usr/local/lib -lprotoc -lprotobuf -lpthread I can run my program and it runs perfectly fine. However, I would like the debug capabilities of the Clion IDE. I tried putting in the compiler flags in the CMake file. It looks like this: (Edit: Per request the image is now in text) cmake_minimum_required(VERSION 3.21) project(Protobuf) set(CMAKE_CXX_STANDARD 23) set(GCC_COVERAGE_COMPILE_FLAGS "-pthread -I/usr/local/include -pthread -L/usr/local/lib -lprotoc -lprotobuf -lpthread") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${GCC_COVERAGE_COMPILE_FLAGS}" ) add_executable(Protobuf main.cpp data.pb.h data.pb.cc) Am I missing something?
Thanks to the comment of "Some programmer dude" its clear that this is not a compiler issue but a linker issue. Therefore putting linker flags into the compiler flags results in it not operating. Thanks to DevSolar I made some more changes to the CMake and it now looks like this: cmake_minimum_required(VERSION 3.21) project(Protobuf) include(FindProtobuf) find_package(Protobuf REQUIRED) include_directories(${PROTOBUF_INCLUDE_DIR}) set(CMAKE_CXX_STANDARD 23) set(GCC_COVERAGE_COMPILE_FLAGS "-pthread -I/usr/local/include -pthread") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${GCC_COVERAGE_COMPILE_FLAGS}" ) add_executable(Protobuf main.cpp data.pb.h data.pb.cc) target_link_libraries(Protobuf ${PROTOBUF_LIBRARY}) By using the find_package and include_directories, I am now able to link the protobuf library without any compiler-specific flags.
73,274,651
73,282,916
why dbghelp cannot resolve symbol from managed callstack?
What's the difference between managed callstack and native callstack, why cannot resolve the symbol from managed callstack by dbghelp? can anyone tell me the basic reason?
When a native exe runs, windows maps the exe (and dll's) into memory using memory mapped files functionality (not that that matters). So when your program runs, you have a module address which is the base address that the native exe (or dll) image is loaded from (e.g. module address points to the first byte in the exe/dll file and so on). So when you have a address from a stack walk, you "know" what module the address is from based on the loaded module list as the address will be in a range one of the modules address ranges. It then knows the offset into the exe file (i.e. address - module address == offset into exe). dbhelp uses this address to find the module and then uses the offset into the exe to find the symbol (the pdb has a table of address ranges to symbols). So this is how it works for a native running code. Why you can't work for managed exe is because how managed code works. Compiled managed code not native code, it's IL. A managed EXE is a small native wrapper around a IL assembly. The native wrapper is used to "start" the .net runtime and run the entry point in the IL assembly. The .net runtime uses JIT to convert the IL to native code. It does this by allocating memory, generating the native code and marking the memory page as excutable, then jumping to it. So when these addresses show up in a stack walk, it's doesn't map to ANY loaded native module (as it doesn't). So you just see a address it can't map to any PDB file. So to be able to map this unknown addresses to a managed symbol, you need to have: internal knowledge of how the managed runtime works access to memory of the process to be able to lookup it's internal runtime tables to resolve these unknown addresses to a managed symbol (this is the reason why you need a full memory dump it resvole .net stacks) So dbghelp is only for native symbol mapping and knows nothing about managed stack traces. The managed stack traces of memory dumps (or live process memory) needs knowage / access to the internal managed runtime tables to be able to resolve the temporary executable memory pages to managed symbols.
73,275,059
73,275,100
Cannot run .exe file from VS Code Terminal / Powershell
In my folder are these files: hello.cpp hello.exe hello.ilk hello.pdb When I try to execute the .exe file within a terminal in VS Code I receive this: C:\Users\User\Documents\VS_Code> hello.exe hello.exe : The term 'hello.exe' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 + hello.exe + ~~~~~~~~~ + CategoryInfo : ObjectNotFound: (hello.exe:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException Suggestion [3,General]: The command hello.exe was not found, but does exist in the current location. Windows PowerShell does not load commands from the current location by default. If you trust this command, instead type: ".\hello.exe". See "get-help about_Command_Precedence" for more details. When I'm running it from the developer prompter from Visual Studio it works.
I think your issue can be solved by just looking at the error suggestion. It says to use .\hello.exe . Hope this helps :)
73,275,424
73,275,936
Is there any way to implicitly convert parameters in template functions
I'm using lazy_importer recently but I get a strange error when calling functions; for example: LI_FN(WriteFile)(DiskHandle, Sector, sizeof(Sector), &Bytes, NULL); I get this error: C2664,Cannot convert parameter 5 from '_Ty' to 'LPOVERLAPPED' The below code fixes this: LI_FN(WriteFile)(DiskHandle, Sector, sizeof(Sector), &Bytes, (LPOVERLAPPED)NULL); I was wondering if I could be more lazy and not add the (LPOVERLAPPED) manually, but let the compiler do it for me?
The issue occurs because of your use of the NULL token, which is basically a C language macro for a null pointer. Relevant cppreference page. Typically, for a C compilation, NULL is defined as a void* pointer with a value of zero, like this (the exact definition can vary between compilers and platforms, but the C Standard requires that NULL be defined as a "null pointer constant"): #define NULL ((void *)0) However, in C++, NULL is generally defined as an integer literal (although the C++ Standard does allow it to be defined as nullptr): #define NULL 0 Thus, there is no implicit conversion from NULL to a pointer type and, if you use that token, you need to add an explicit cast to a pointer. In C++ programs, you should really be using the in-built nullptr literal when initialising pointers to a null value, or passing null pointer arguments. This is implicitly convertible to a null pointer of any type.
73,276,161
73,276,890
How to use `boost::dynamic_properties` with vector valued property maps?
I would like to include a map<string, vector<int>> in a boost::dynamic_properties property: #include <map> #include <string> #include <vector> #include <boost/property_map/dynamic_property_map.hpp> #include <boost/property_map/property_map.hpp> auto main() -> int { auto name2numbers = std::map<std::string, std::vector<int>>{}; auto property_map = boost::associative_property_map{name2numbers}; auto dynamic_properties = boost::dynamic_properties{}; dynamic_properties.property("test", property_map); } Compiling with g++ fails with the error no match for ‘operator<<’ for ostringstream and vector<int>: error: no match for ‘operator<<’ (operand types are ‘std::ostringstream’ {aka ‘std::__cxx11::basic_ostringstream<char>’} and ‘boost::associative_property_map<std::map<std::__cxx11::basic_string<char>, std::vector<int> > >::value_type’ {aka ‘std::vector<int>’}) 180 | out << get_wrapper_xxx(property_map_, any_cast<typename boost::property_traits<PropertyMap>::key_type>(key_)); | ~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ So I decided to add a template for general vector streaming above main: template <typename OStream> auto operator<<(OStream& output_stream, std::vector<int> const& vec) -> OStream& { for (auto item : vec) { output_stream << item << " "; } return output_stream; } Unfortunately, that does not help. Neither does writing a function explicitly for ostringstream. I always get the same error and my template does not appear in the list of candidates tried by the compiler. How can I actually tell boost::dynamic_properties how to write a vector of integers or at least make it try my template?
If you want to “hack” solution by providing operator<< for a standard library type, you need to declare it in one of the associated namespaces for argument dependent lookup. Specifically you would need to declare this overload inside namespace std (because both std::vector and std::o stream are declared there). However I would suggest taking more control over the specific serialization format of your property-map by using a transform_value_propertymap or function_property_map instead. See for some examples: Ouput (for GraphViz) Boost Graph vertices with their property, using as bundled property a class with private variables exporting a vector variable to graph via boost graph Weight map as function in Boost Graph Dijkstra algorithm A search on this site will probably reveal more relevant answers by yours truly
73,276,389
73,276,580
How to Store and retrieve the the correct Type of DerivedClass Pointer To/From Map of BaseClass Pointer
Hello i have question about Maps and Inheritance. I have Map of BaseClass Pointer: std::map<int,std::shared_ptr<Game>> GamesByID; and inserted Derived Class Pointer into it like: GamesByID.insert(make_pair(ID,std::make_shared<ActionGame>(ID,Title,Metacritic,Recommendations,Price,lvl))); now i wanted to count how many ActionGame Pointer i had in my map with somthing like that for (auto& e : GamesByID) { if(typeid(e) == typeid(SurvivalGame)){ ++count; }else{ cout << typeid(e).name() << " typeid" <<endl; } } But in the map ther are only BaseClass Pointer, now what is my mistake do i instert them wrong ?
The map contains pointers of type "Game" nothing to do with derived class, the name to store a derived class with a pointer of base class is called polymorphism, You will need a function to return something like a flag to get what type of class it is. What I'm trying to say is that polymorphism will let you create a pointer variable with the type of the base class that can hold the address of a derived class the pointer itself in the map is not a derived class object class baseClass { protected: string type = "baseClass"; public: string getClassType() { return this->type; } } class derivedClass : public baseClass { derivedClass() { this->type = "derivedClass"; } } Here I gave you an example where the base class has a type variable where you store the type and now if you check the type member of a baseClass* you will get a string telling you the type since both the variable and function to return the variable are in base class
73,276,625
73,279,817
How to resolve "Make sure the web address //ieframe.dll/dnserrordiagoff.htm# is correct" error in wxWebView (wxWidgets)
I am using wxWebView for showing our page content and when I don't have any content for the page, i.e. page is blank, I see the following error: I have my own file system handler class derived from wxWebViewHandler like below and in GetFile function, I set the content of page. Everything works fine except when page does not have any content. Maybe I should return something else. struct WxHtmlFSHandler: public wxWebViewHandler { WxHtml* dst_; WxHtmlFSHandler( const wxString& scheme, WxHtml* dst ): wxWebViewHandler( scheme ), dst_( dst ) { } wxFSFile* GetFile( const wxString& uri ) override; ~WxHtmlFSHandler() { dst_ = nullptr; } }; ... if( dst_ && !uri.empty() ) { if( uri.Contains( dst_->defaultURL_ ) ) { // load the page's content //if( !dst_->currentPage_.empty() ) return new wxFSFile( new wxMemoryInputStream( dst_->currentPage_.data(), dst_->currentPage_.size() ), uri, wxT( "text/html" ), dst_->currentAnchor_ #if wxUSE_DATETIME , wxDateTime::Now() #endif ); ... } I am also using IE engine for now. #if wxUSE_WEBVIEW_IE wxWebViewIE::MSWSetEmulationLevel( wxWEBVIEWIE_EMU_IE11 ); #endif I am using wxWidgets 3.1.5 on Win 10.
So the problem is when the page content is empty. So I just tried to add a space char to my memory input stream like below and see the effect. It seems working! Basically I replaced return new wxFSFile( new wxMemoryInputStream( "", 0 ), uri, wxT( "text/html" ), dst_->currentAnchor_ #if wxUSE_DATETIME , wxDateTime::Now() #endif ); with return new wxFSFile( new wxMemoryInputStream( " ", 1 ), uri, wxT( "text/html" ), dst_->currentAnchor_ #if wxUSE_DATETIME , wxDateTime::Now() #endif ); and now page is blank and does not show anything as expected. I don't know whether this hack is good or even correct, so if anyone has a better answer, please let me know.
73,278,382
73,284,613
RocksDB: iterator upper bound not working as expected
I need to store a bunch of values in RocksDB (using v6.20.3) with the keys in the following format: PREFIX_<INTEGER_ID>. The INTEGER_ID is a running sequence of numbers from 0 to N. I use a serialize_uint32_t function which converts the integer IDs to lexographic ordered strings (since I need to iterate the integers in order). Since N could be large, I wanted to iterate on the RocksDB entries until a smaller integer value K by setting the iterate_upper_bound property of the iterator. However, when I enable this property, the iteration does not happen. Here's a small, fully reproduceable program below. When I comment the upper bound setting line out, the iterator works and the values are printed correctly. UPDATE: Noticed another strange thing: the code snippet with upper bound works fine on Debug mode, but not on Release with -O2. #include <iostream> #include <rocksdb/db.h> #include <rocksdb/options.h> using namespace std; static std::string serialize_uint32_t(uint32_t num) { unsigned char bytes[4]; bytes[0] = (unsigned char) ((num >> 24) & 0xFF); bytes[1] = (unsigned char) ((num >> 16) & 0xFF); bytes[2] = (unsigned char) ((num >> 8) & 0xFF); bytes[3] = (unsigned char) ((num & 0xFF)); return std::string(bytes, bytes+4); } int main() { const std::string state_dir_path = "/tmp/local-data"; system("rm -rf /tmp/local-data && mkdir -p /tmp/local-data"); rocksdb::DB *db; rocksdb::Options options; rocksdb::WriteOptions write_options; options.create_if_missing = true; rocksdb::Status s = rocksdb::DB::Open(options, state_dir_path, &db); if(!s.ok()) { std::cout << "Error while initializing store: " << s.ToString() << std::endl; return 1; } std::string key_prefix = "PREFIX_"; for(size_t i = 0; i < 9; i++) { auto key_val = key_prefix + serialize_uint32_t(i); db->Put(write_options, key_val, "HELLO:"+std::to_string(i)); } std::cout << "Wrote 9 entries." << std::endl; // Try to iterate only 6 entries rocksdb::ReadOptions read_opts; rocksdb::Slice upper_bound(key_prefix + serialize_uint32_t(6)); read_opts.iterate_upper_bound = &upper_bound; // does NOT work when set rocksdb::Iterator *iter = db->NewIterator(read_opts); iter->Seek(key_prefix + serialize_uint32_t(0)); while(iter->Valid() && iter->key().starts_with(key_prefix)) { std::cout << iter->value().ToString() << std::endl; iter->Next(); } delete iter; delete db; return 0; }
I'm not sure whether it is the root cause but the code has a bug. rocksdb::Slice is similar to std::string_view. It points to a char array but doesn't maintain it. After upper_bound is constructed, key_prefix + serialize_uint32_t(6) might get destroyed, so read_opts.iterate_upper_bound points to a destroyed memory. The argument of iter->Seek() might not be safe either, since Seek() also accepts rocksdb::Slice, rather than std::string.
73,279,043
73,279,108
How to use the same object instance when creating other objects?
I'm new to C++ and started playing with references, which led me to the following code: #include <iostream> #include <unordered_map> class Wrapper { private: std::unordered_map<std::string, int> map; public: void add(std::string &key, int value) { map[key] = value; } int get(std::string &key) { return map[key]; } }; class Writer { private: Wrapper wrapper; public: explicit Writer(const Wrapper &wrapper) : wrapper(wrapper) { std::cout << "Writer: " << &wrapper << std::endl; } void write(std::string key, int value) { wrapper.add(key, value); } }; class Reader { private: Wrapper wrapper; public: explicit Reader(const Wrapper &wrapper) : wrapper(wrapper) { std::cout << "Reader: " << &wrapper << std::endl; } int read(std::string key) { return wrapper.get(key); } }; My main function: int main() { Wrapper wrapper; Writer writer(wrapper); Reader reader(wrapper); writer.write("key", 123); std::cout << "Value: " << reader.read("key") << std::endl; } I pass a reference to the same instance of the Wrapper class when I create an instance of Writer and Reader. I expected that the value added by the writer should also be available to the reader, since they use the same wrapper instance. However, the read("key") call returns 0 because the key is unknown. What am I doing wrong and how can I achieve the desired behavior?
member variable must also be declared as reference, in both reader and writer class Writer { private: Wrapper & wrapper; } class Reader { private: Wrapper & wrapper; }
73,279,395
73,282,533
How can I resize QTableView row according to specific cell value?
I want to resize the row height according to a specific column value. For example, the table I want to change is here: At row 10, row height is resized by the third column value. But at row 11 it is resized by the second column value. I want to resize row height by only the third column value. Is there a way to do this? Thank you. This is my code for this QTableView ui->tableView->setModel(modal); ui->tableView->hideColumn(0); ui->tableView->resizeColumnsToContents(); ui->tableView->resizeRowsToContents(); ui->tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch); ui->tableView->horizontalHeader()->setStyleSheet("QHeaderView { font-size: 18pt; color:#002B5B; font-weight: bold; }");
I haven't actually tried it myself, but from looking at the Qt source code (in particular the source code for QTableView::rowHeight(int) const and QHeaderView::sectionSizeFromContents(int) const), it looks like you could do something like: const int addressColumnLogicalIndex = 1; // i.e. 2nd column in the table const int fixedRowHeight = 18; // or whatever fixed height you want the address-column to use model()->setHeaderData(addressColumnLogicalIndex, Qt::Vertical, QSize(0, fixedRowHeight), Qt::SizeHintRole);
73,279,562
73,280,255
How to explicitly specify template arguments for multiple parameter packs
I am trying to understand the following code: template <class...Ts, class...Us> void f(void) {}; int main() { f<int, char, float, double>(); } I don't know how template argument deduction deduces Ts and Us. In this answer, I learned that parameter packs are greedy, so Ts will match all specified arguments: [ Ts = int, char, float, double ]. But what about Us: it has not been deduced yet? or what happens in this case? I expect that the compiler throws a deduction error since it cannot figure out what Us is expanded to. Can I somehow, in the template argument-list, tell the compiler that I need Ts to be int, char, and Us to be float, double? how I can do that? I mean, can the call expression be something like that: f<{int, char}, {float, double}>(); I found out that when I edit the above code to be as follows, this will fit my needs: template <class...> struct S{}; template <class...Ts, class...Us> void g(S<Ts...>, S<Us...>) { }; int main() { S<int, char> s1; S<float, double> s2; g(s1 ,s2); } But I still need to understand why in this case Ts is [int, char], and Us is [float, double]. What I think in this case is that: Since parameter packs are greedy, template argument deduction deduces Ts as [S<int, char>, S<float, double>] and Us is left off un-deduced or just empty. Right? This makes me think that First, [int, char] gets substituted in the place of Ts... in the first function parameter S<Ts..>, so it gets expanded into S<int, char>. Then [float, double] gets substituted in the place of Us... in the second function parameter S<Us..>, so it gets expanded into S<float, double>. Second, template argument deduction deduces Ts as [int, char] and Us as [float, double]. Is my understanding correct in this case?
Regarding the second part of the question (second example). Template argument deduction deduces parameter packs Ts as [int, char], and Us as [ float, double ] the same way it deduces T if you have the following: template <class> struct B {}; template <class T> void h(B<T>) .. and you call h(B<int>()), template argument deduction is applied as follows: P = B<T>, A = B<int> -> [ T = int ] not [ T = B<int> ] The same is applied in the second example: P1 = S<Ts...>, A1 = S<int, char> --> [ Ts = int, char ]; P2 = S<Us...>, A2 = S<float, double> --> [ Us = float, double ];
73,279,731
73,279,793
variadic arguments which are all a specialization of a template type
We can validate at compile time that an input to a function is a specialization of a template. I.E the following code validates that the input for f is some specialization of struct Holder. template<typename T> struct Holder<T> {...}; template<typename T> void f(Holder<T> h) {...}; I want to validate that a set of variadic arguments are a specialization of a template. More precisely I want to differentiate between two consecutive sets of variadic arguments - a set which is a specialization of a template, and a set which isn't. Following is an example of how it might have looked like if the syntax allowed it to - template<...Args1, ...Args2> void f(Holder<Args1>.... args_which_are_specializations_of_Holder, Args2... args_which_are_not) { use_holders(args_which_are_specializations_of_Holder...); use_rest(args_which_are_not...); return; } Is this possible ? Thanks,
You can store the args in a tuple and calculate the index of the last Holder argument, then extract the Holder and normal arguments by index and forward them to the corresponding function. #include <tuple> template<class T> constexpr bool is_holder = false; template<class T> constexpr bool is_holder<Holder<T>> = true; template<class... Args> void f(Args... args) { constexpr auto holder_index = (is_holder<Args> + ... + 0); auto args_tuple = std::tuple(args...); [&args_tuple]<auto... Is>(std::index_sequence<Is...>) { use_holders(std::get<Is>(args_tuple)...); }(std::make_index_sequence<holder_index>{}); [&args_tuple]<auto... Is>(std::index_sequence<Is...>) { use_rest(std::get<Is + holder_index>(args_tuple)...); }(std::make_index_sequence<sizeof...(Args) - holder_index>{}); } Demo
73,279,841
73,280,028
One liner template type changer
I'm sorry for the title, I don't know how to call it... I'm trying to make a one liner of the caller() function (C++20). template <typename T> void func() { std::cerr << typeid(T).name() << std::endl; } void caller(const int &_i) { switch(_i) { case 1: func<uint8_t>(); break; case 2: func<uint16_t>(); break; case 3: func<uint32_t>(); break; case 4: func<uint64_t>(); break; } } int main() { caller(1); caller(2); return 0; } I tried with struct helper but it seems this case do not fit. I also tried a different approach with caller<i>() and the use of std::conditional_t, but did not find how to use it in this specific case. template <size_t ID> void func() { using T = std::conditional_t<ID==0, uint8_t, [...]>; std::cerr << typeid(T).name() << std::endl; } Is there multiple ways to do this, and if so, which are they?
If you can provide the value to caller at compile time, you can do something like this: template<std::size_t> struct int_type_id; template<> struct int_type_id<0> { using type = std::uint8_t; }; template<> struct int_type_id<1> { using type = std::uint16_t; }; template<> struct int_type_id<2> { using type = std::uint32_t; }; template<> struct int_type_id<3> { using type = std::uint64_t; }; template <std::size_t ID> void caller() { using T = typename int_type_id<ID>::type; func<T>(); // you can reduce that to a one liner: // func<typename int_type_id<ID>::type>(); } A true one liner for that could be using std::tuple and std::tuple_element_t: template <std::size_t ID> void caller() { using T = std::tuple_element_t< ID, std::tuple<std::uint8_t, std::uint16_t, std::uint32_t, std::uint64_t> >; func<T>(); } Then call it like that: int main() { caller<1>(); caller<2>(); return 0; }
73,279,958
73,281,488
QString::replace doesnt replace
Problem I am trying to convert a string to a C string. In doing so, I need to replace " with \". I use the following code to do this: QString Converter::plain2C(const QString &in) { QString out; // Split input in each line QStringList list = in.split(QChar('\n')); for (int i = 0; list.length() > i; i++) { // Go throught each line of the input QString line = list[i]; // Thats the line line.replace(QChar('\\'), QLatin1String("\\\\")); // replace \ with \\ line.replace(QChar('"'), QLatin1String("\\\"")); // replace " with \" // For printf() if(escapePercent) line.replace(QChar('%'), QLatin1String("%%")); // If option "Split output into multiple lines" is active add a " to the output if (multiLine) out.append(QChar('"')); // append the line to the output out.append(line); // append a "\n" to the output because we are at the end of a line if (list.length() -1 > i) out.append(QLatin1String("\\n")); // If option "Split output into multiple lines" is active add a " and \n to the output if (multiLine) { out.append(QChar('"')); out.append(QChar('\n')); } } if (!multiLine) { out.prepend(QChar('"')); out.append(QChar('"')); } return out; } However, " is still there without a \ before. Information Qt Version 5.15.3 C++17 Edit The application is used to enter a normal string copied from the Internet and get as a result a string that can be copied into a C/C++ program. More code void Converter::run() { if (_from != From::NotSupportet && _to != To::toInvalid) { QString out; // More code obove and below else if (_from == From::Plain) { switch (_to) { case To::toCString: out = plain2C(_in); break; // Emits the ready string which is applied direct to a QPlainTextEdit emit htmlReady(out); } } Edit 2 Added more comments to the code
It works now. The problem was the line above: line.replace(QChar('\'), QLatin1String("\\\\")); // replace \ with \\ The problem was that the comment ended with 2 \. That somehow disabled the next line or something like that. Anyway, this is the working code: QString Converter::plain2C(const QString &in) { QString out; // Split input in each line QStringList list = in.split(QChar('\n')); for (int i = 0; list.length() > i; i++) { // Go throught each line of the input QString line = list[i]; // Thats the line line.replace(QChar('\\'), QLatin1String("\\\\")); // replace "\" with "\\" line.replace(QChar('"'), QLatin1String("\\\"")); // replace " with \" // For printf() if(escapePercent) line.replace(QChar('%'), QLatin1String("%%")); // If option "Split output into multiple lines" is active add a " to the output if (multiLine) out.append(QChar('"')); // append the line to the output out.append(line); // append a "\n" to the output because we are at the end of a line if (list.length() -1 > i) out.append(QLatin1String("\\n")); // If option "Split output into multiple lines" is active add a " and \n to the output if (multiLine) { out.append(QChar('"')); out.append(QChar('\n')); } } if (!multiLine) { out.prepend(QChar('"')); out.append(QChar('"')); } return out; }
73,280,301
73,281,511
QT/C++ Call function of a widget using a slot
Consider following main.cpp (the only file of the whole Qt-project): #include <QApplication> #include <QWidget> #include <QPushButton> #include <QVBoxLayout> #include <QLabel> #include <QObject> #pragma once class collectedFunctions : public QObject { Q_OBJECT public: collectedFunctions(QObject* parent = 0) {}; ~collectedFunctions() {}; public slots: void setFunc() { //Calculate 2+2 and change text of the label accordingly } }; #include "main.moc" int main(int argc, char* argv[]) { QApplication app(argc, argv); QWidget window; window.resize(200, 200); window.setWindowTitle("Test-GUI"); QVBoxLayout layout(&window); QPushButton button(&window); button.setText("Test"); button.show(); QLabel *label = new QLabel(&window); label->setText("Hello"); collectedFunctions testingFuncs; QObject::connect(&button, &QPushButton::clicked, &testingFuncs, &collectedFunctions::setFunc); layout.addWidget(&button); layout.addWidget(label); window.show(); return app.exec(); } My goal with this code is to create a slot that runs a function which the programmer defines (similar to the pyqt-implementation of the signals and slots system). The code above successfully compiles, not throwing any errors and so far meeting my expectations. Yet as soon I want to manipulate a widget (which in this case is the label), the setfunc-slot does not find the defined label. How can I manipulate a widget using this slot (e.g. using setText() at a label or addItems() at a combobox) or generally have them being recognized in the slot. Update: Thanks to the solution of this question, I figured that I could simply use a lambda instead of the Q_OBJECT makro, so I removed the header-code and then changed the connect from the Button to following: QObject::connect(&button, &QPushButton::clicked, [&label](){ int num = 2 + 2; string text = "2+2 = "; text += std::to_string(num); QString qtext = QString::fromStdString(text); label->setText(qtext); });
you shouldn't use the Q_OBJECT macro in main.cpp. The Q_OBJECT macro must appear in the private section of a class definition that declares its own signals and slots or that uses other services provided by Qt's meta-object system. The moc tool reads a C++ header file. If it finds one or more class declarations that contain the Q_OBJECT macro, it produces a C++ source file containing the meta-object code for those classes. Among other things, meta-object code is required for the signals and slots mechanism, the run-time type information, and the dynamic property system. The C++ source file generated by moc must be compiled and linked with the implementation of the class. When you have your class defined in .cpp file instead of .h file moc fails to process it properly. you need a separate file for class: in collectedfunctions.h #pragma once #include <QObject> class collectedFunctions: public QObject { Q_OBJECT public: collectedFunctions(QObject *parent = 0); ~collectedFunctions(); public slots: void setFunc(); }; and in collectedfunctions.cpp #include "collectedfunctions.h" #include <QDebug> collectedFunctions::collectedFunctions(QObject *parent) { } collectedFunctions::~collectedFunctions() { } void collectedFunctions::setFunc() { qDebug() << "2+2 = " << 2 + 2; } and in your main.cpp #include <QApplication> #include <QWidget> #include <QPushButton> #include <QVBoxLayout> #include <QLabel> #include "collectedfunctions.h" int main(int argc, char *argv[]) { QApplication app(argc, argv); QWidget window; window.resize(200, 200); window.setWindowTitle("Test-GUI"); QVBoxLayout layout(&window); QPushButton button(&window); button.setText("Test"); button.show(); QLabel *label = new QLabel(&window); label->setText("Hello"); collectedFunctions testingFuncs; QObject::connect(&button, &QPushButton::clicked, &testingFuncs, &collectedFunctions::setFunc); layout.addWidget(&button); layout.addWidget(label); window.show(); return app.exec(); } don't forget to add QT +=core gui widgets in your .pro file. Result: If you want to change QLabel Text : in collectedfunctions.h #pragma once #include <QObject> class collectedFunctions: public QObject { Q_OBJECT public: explicit collectedFunctions(QObject *parent = 0); ~collectedFunctions(); signals: void updateLable(int num); public slots: void setFunc(); private: int num = 0; }; and in collectedfunctions.cpp #include "collectedfunctions.h" #include <QDebug> collectedFunctions::collectedFunctions(QObject *parent) { } collectedFunctions::~collectedFunctions() { } void collectedFunctions::setFunc() { qDebug() << "2+2 = " << 2 + 2; num++; emit updateLable(num); } and in your main.cpp #include <QApplication> #include <QWidget> #include <QPushButton> #include <QVBoxLayout> #include <QLabel> #include "collectedfunctions.h" int main(int argc, char *argv[]) { QApplication app(argc, argv); QWidget window; window.resize(200, 200); window.setWindowTitle("Test-GUI"); QVBoxLayout layout(&window); QPushButton button(&window); button.setText("Test"); button.show(); QLabel *label = new QLabel(&window); label->setText("Hello"); collectedFunctions testingFuncs; QObject::connect(&button, &QPushButton::clicked, &testingFuncs, &collectedFunctions::setFunc); QObject::connect(&testingFuncs, &collectedFunctions::updateLable, [&label](int num) { qDebug() << "Number = " << num; label->setText(QString::number(num)); }); layout.addWidget(&button); layout.addWidget(label); window.show(); return app.exec(); } you can see:
73,280,363
73,280,478
Why is this code involving the ternary operator getting an error in C, but not in C++?
I get "error: lvalue required as left operand of assignment" for "x=k" in C, but the code runs without an error in C++. I don't understand why C is giving me this error, while C++ doesn't. #include <stdio.h> int main() { int j=10, k=50, x; j<k ? x=j : x=k; printf("%d",x); }
In C, the ternary operator ?: has higher precedence than the assignment operator =. So this: j<k ? x=j : x=k; Parses as this: ((j<k) ? (x=j) : x)=k; This is an error in C because the result of the ternary operator is not an lvalue, i.e. it does not denote an object and so can't appear on the left side of an assignment. C++ however has ?: and = at the same precedence level, so it parses the expression like this: j<k ? x=j : (x=k); Which is why it works in C++. And actually, C++ does allow the result of the ternary operator to be an lvalue, so something like this: (j<k ? a : b ) = k; Is legal in C++. You'll need to add parenthesis to get the grouping you want: j<k ? x=j : (x=k); Or better yet: x = j<k ? j : k;
73,280,646
73,280,767
best strategy for ensuring no copies in return by value
I'm using c++17, but I don't get to choose my compiler. Suppose I have type S with move and copy semantics. Typically for me S will be a std::vector of some aggregate type. I'm also using a function g which returns an S by value: S g(int x); Suppose further I'm writing this function, f, with a single return statement: S f(int y) { ... return g(x);} I have a choice for the final return: (i) return g(x); (ii) return S{g(x)}; (iii) S tmp = g(x); return tmp; As I understand it, (ii) will guarantee copy elision, so the move construction of S from g will be constructed in the caller's memory. (iii) Is quite likely to guarantee NRVO, named return value optimisation, so tmp is move constructed, again in the caller's memory. But what can be said about (i)? Which would you choose, given the need for good performance on any target? Or does it make no difference?
Use (i). (i) and (ii) are the same, both guarantee zero copies/moves since C++17. An extra constructor call in (ii) doesn't help at all, it's just one more thing to elide with the mandatory RVO. (iii) is worse: it guarantees a move at worst, or no move if the compiler performs NRVO (in which case it becomes the same as (i) and (ii)).
73,280,748
73,282,307
std::variant having for possible type a ptr to an array of a given type. Can I store more information that just type?
I am looking at using std::variant to store basic types such as float, int, float2, float2, bool2, bool4, etc. which is rather trivial, but I would also ideally like to construct variant objects holding a pointer to a typed array. I came up with this solution, which compiles and run without crashing (which doesn't mean a bug isn't in there)): #include <variant> #include <vector> #include <iostream> #include <algorithm> struct float3 { float x, y, z; float3() : x(0), y(0), z(0) {} float3(const float& r) : x(r), y(r), z(r) {} }; int main() { typedef std::variant<float, float3, float3*> Variant; std::vector<float3> v(3); std::generate(v.begin(), v.end(), [n=0] () mutable { return ++n; }); Variant var(&v[0]); if (float3** ptr = std::get_if<float3*>(&var)) { std::cout << "this is a float3*: " << (*ptr)[0].x << std::endl; } else { std::cout << "didn't recognize type\n"; } return 0; }; However, by doing so, I lose some additional data that I'd like to store alongside this particular variant type such as the size of the array (in a number of bytes for example). Would it best to write my own custom Variant class and create a constructor like this: class Variant { public: enum Type { ... FLOAT, FLOAT2, FLOAT3, ... }; Variant(std::shared_ptr<void*>& ptr, Type type, size_t size, size_t stride, ...) : type(Type), data(new Data(ptr, size, stride, ...)) {} std::shared_ptr<Data> data; }; With class Data class Data { public: Data(const std::shared_ptr<void*>& ptr, size_t nb, size_t stride, ...) : ptr(ptr), nbytes(nb), stride(stride) ... {} std::shared_ptr<void*> ptr; size_t nbytes; size_t stride; ... } Or can I still somehow make it work with std::variant? Any suggestions would be greatly appreciated.
This "pointer plus size" type already exists since C++20 and it's called std::span. You can use std::variant<float, float3, std::span<float3>> If you want an array of many different types, you could use std::variant<std::span<float3>, std::span<float2>, std::span<bool2>, etc>. Notice that you do have to write all the types in the variant (might want to make it a typedef), but you don't have to write special code for each type as you can use visit with a template: std::variant<std::span<float3>, std::span<float2>, std::span<bool2>> myVariant = ........; // print all the elements. auto parameter makes a lambda with a template function. // a separate copy is compiled for each type. std::visit(myVariant, [](auto& span) { for(auto& item : span) std::cout << item << std::endl; }); std::span is for an array that someone else will delete - if you want the variant to delete its own memory, use std::vector
73,280,786
73,314,596
DLL not found in redistributable (biddll.dll)
I’m having difficulty getting the sample code for tws api running. I’ve successfully run it on a borrowed laptop but the same version fails on my own windows 10 laptop. When running on Release mode in Win32, I get the popups The code execution cannot proceed because biddll.dll was not found. Reinstalling the program may fix this problem. and The procedure entry point ?cancelOrder@EClient@@QAEXJ@Z could not be located in the >dynamic link library C:\Eclipse-workspace\TWS >API\samples\Cpp\TestCppClient\ReleaseTestCppClient.exe. I’ve read through several questions similar to this. I’ve tried installing the Visual C++ Redistributable for Visual Studio 2022 for both x86 and x64 from here: https://learn.microsoft.com/en-US/cpp/windows/latest-supported-vc-redist?view=msvc-170. I’ve tried loading biddll.dll from another folder but it gives the message “Module was built without symbols.”. I’ve run “sfc /scannow” for broken files. The issue persists. biddll.dll still seems to not be anywhere in the system files or the API files. The only version is the one I copied from another version of the project.
Thanks for your suggestions. I uninstalled TWS API and reinstalled it. I made sure to build for Release. It sounds like there was a mismatch between some debug libraries and it started pulling them instead. There may have been some unexpected behavior from installing several versions while troubleshooting as well.
73,281,227
73,434,784
How to instantiate templated functors F<D> over multiple functors F1,F2 and multiple template parameters D1,D2?
I need to instantiate a bunch of functors template<typename DataType> struct Functor1{ int a; Functor1(int a_){ a = a_; } // __device__ void operator()(DataType &elem) elem.x +=1; } }; template<typename DataType> struct Functor2{ int a; Functor2(int a_){ a = a_; } // __device__ void operator()(DataType &elem) { elem.x +=10; } }; for Cuda by a set of structs D1, D2...: struct D1{ int x; }; struct D2{ int x; int y; }; I want automatically and explicitly instantiate all of them: template class Functor1<D1>; template class Functor1<D2>; template class Functor2<D1>; template class Functor2<D2>; I want a macros/metaprogrammic trick the code above: #define DATATYPE_LIST(D1)(D2) #define FUNCTOR_LIST (Functor1)(Functor2) EXPLICIT_FUNCTOR_INSTANTIATION(FUNCTOR_LIST, DATATYPE_LIST) How to do that using macroses or SFINAE?
I want a macros/metaprogrammic trick the code above Here is a way to do this using templates instead of macros. The below program works for arbitrary number of Functors and Ds. See the different instantiations at the end of this answer, for different combinations of Functors and Ds. template<template<typename>typename Functor, template<typename>typename... Functors, typename... Args> void f(Args... args) { int i = (Functor<Args>(55)(args),...,1); //instantiate for the first parameter Functor with all of args if constexpr(sizeof...(Functors)>0) { f<Functors...>(args...); //call recursively for remaining Functors with all of args } } int main() { std::cout << "Test 1: "<< std::endl; f<Functor1, Functor2>(D1(), D2()); std::cout <<"--------------------------------------" << std::endl; std::cout << "Test 2: "<< std::endl; f<Functor1, Functor2, Functor3>(D1(), D2()); std::cout <<"--------------------------------------" << std::endl; std::cout << "Test 3: "<< std::endl; f<Functor1, Functor2>(D1(), D2(), D3()); std::cout <<"--------------------------------------" << std::endl; std::cout << "Test 4: "<< std::endl; f<Functor1, Functor2, Functor3>(D1(), D2(), D3()); std::cout <<"--------------------------------------" << std::endl; } Working demo Below are given(output of the above program) the instantiations that will be generated due to different call expressions. Test 1: template Functor1<D1> template Functor1<D2> template Functor2<D1> template Functor2<D2> -------------------------------------- Test 2: template Functor1<D1> template Functor1<D2> template Functor2<D1> template Functor2<D2> template Functor3<D1> template Functor3<D2> -------------------------------------- Test 3: template Functor1<D1> template Functor1<D2> template Functor1<D3> template Functor2<D1> template Functor2<D2> template Functor2<D3> -------------------------------------- Test 4: template Functor1<D1> template Functor1<D2> template Functor1<D3> template Functor2<D1> template Functor2<D2> template Functor2<D3> template Functor3<D1> template Functor3<D2> template Functor3<D3> -------------------------------------- This also work for asymmetric call expressions like: f<Functor1, Functor2, Functor3>(D1(), D2(), D3(), D4()); etc.
73,282,147
73,290,794
Throwing exception in constructor before member initializer list?
As an example, say I have the class class A{ B& foo; }; and I want to initialize this class with a constructor that takes in a vector and an index (just for example). So I get explicit A(std::vector<B>& lst, int index): foo(lst[index]) {}; However, accessing a random index in the vector is unsafe, since it would be UB if it was out of bounds. So, I throw an exception explicit A(std::vector<B>& lst, int index): foo(lst[index]) { if (index >= lst.size()){ //throw blah blah } }; However, this doesn't actually save me at all, because the member initializer list is ran before the constructor body. So the possible out of bounds access would happen first, and only after that the check runs. My current thoughts to solve this are: Assign values in the constructor body. everything is default constructed first, repeats work I know it's not good practice to store references as class members, but this also means that in general we can't throw on any non-default constructable values class members though I guess it would technically make sense to never be able to throw on a non-default constructable object for exception safety Make this check happen before calling the constructor Hard to enforce Are there any language abilities that let me throw an exception early? And if not, what is standard practice for this situation.
Besides the solutions in the comments, you can use the ternary operator: explicit A(std::vector<B>& lst, int index): foo(lst[index < lst.size() ? index : throw blah_blah()]) {} It requires no helper functions and allows customizing your throw.
73,282,337
73,282,784
Why is my C++ code with file output not working?
I didn't got any errors, but my C++ code is still not working. It's really simple: #include <fstream> #include <iostream> using namespace std; int main() { string a; ofstream fout("char.out"); ifstream fin("char.in"); fin >> a; fout << a; return 0; } char.in after running: uiui char.out after running: Did I missed anything simple in my code? P. S. : I got Norton Antivirus and my project folder is missed from AutoCheck.
in fact for reading and writing you should open and close file but you didn't close. Also you have two files where you have done writing from one file and reading from another file, I wonder how you expect to get the correct output. this is how it should be : #include <fstream> #include <iostream> using namespace std; int main() { string a; ofstream fout("char.out"); // check if file is created if(fout.is_open()){ // do writing in file } else cout << "can not open file\n"; fout.close(); //-----------reading the file---------- // use the same file ifstream fin("char.out"); if(fun.is_open()){ // do reading from file std::cout << a << std::endl; } else cout << "can not open file\n"; fin.close(); return 0; } And if you want to add a line of text to the end of the file, you must add: ofstream fout("filename" , ios::app);
73,282,668
73,282,710
Using an initialized object from one .cpp in another .cpp file without classess
I'm trying to split some functionality between multiple .cpp files and I've got an issue. Let's say, I have: Extra.h #include "CustomClass.h" namespace extraSpace { extern int justInteger; extern CustomClass *complexObject; } Extra.cpp include "Extra.h" int extraSpace::justInteger = 1; CustomClass *extraSpace::complexObject = new CustomClass; complexObject->SomeProperty = 1; // Can't do this Main.cpp include "Extra.h" int main() { std::cout << extraSpace::justInteger << "\n"; std::cout << extraSpace::complexObject->SomeProperty << "\n"; } This code works well for justInteger variable. However, I cannot manipulate complexObject properties in Extra.cpp. Is there any simple workaround here? I thought about creating some InitObject() function, but this would mean that I would have to change the object from Main.cpp, which I would rather not do.
CustomClass *extraSpace::complexObject = new CustomClass; complexObject->SomeProperty = 1; // Can't do this You can use a lamda. CustomClass *extraSpace::complexObject = [] { auto* complexObject = new CustomClass; complexObject->SomeProperty = 1; return complexObject; }();
73,282,921
73,283,549
Find when a particular place in memory is changed in c++
Let's say I have an object MyObject and it has an attribute double MyObject::a. When I initialize a I set it to 0.05, but at some point when I run my code I notice that a is 1.something e-316, even though my code is never supposed to change its value. If I knew an exact place in memory that a occupies, is there a tool that will tell me when exactly this place is overwritten?
As others have already noted, you could use a debugger for this. Most reasonably recent debuggers have some capability to break when a value is written to a particular variable (e.g., Visual Studio calls this a "watchpoint" or "data breakpoint" (depending on what age of IDE you're looking at), if memory serves. Depending on the situation, you might be able to get some useful information by changing your double to a const double: const double value { 0.05 }; Then any code that tries to assign a new value to this variable simply won't compile. If, however, the problem arises from some code doing an out of bounds write, rather than assigning to the value that's getting overwritten, this won't help find that. gdb watchpoints VS data breakpoints
73,283,580
73,283,935
How can I decay const char that is passed as reference to a function with variadic parameters?
I have a function like this: void column(const std::string &value) { ... } void column(float value) { ... } template <class... TColumns> void row(const TColumns &...columns) { ImGui::TableNextRow(); (column(columns), ...); } I am using clang-tidy static analyzer to make sure that my code is always compliant with cpp core guidelines. I am using this function in the following way: // (const char[5], float) row("Hello", 20.5f); My understanding is that, std:string accepts const char * but the first argument of the function call above gets inferred to const char[5]. This causes array decay and I get clang-tidy error that: do not implicitly decay an array into a pointer; consider using gsl::array_view or an explicit cast instead Is it possible to somehow enforce that string argument that is passed is always const char *, not const char[5] or const char[6] etc?
Since you anyways convert a c-string to a string each time you reach this line, it's suggested to have a static string. That is expected to solve the warning as well. #include <iostream> void column(const std::string &value) { } void column(float value) { } template <class... TColumns> void row(const TColumns &...columns) { // ... (column(columns), ...); } int main() { static auto hello = std::string{"Hello"}; row(hello, 20.5f); } However, the best solution is likely to simply turn off the warning - either globally, or as Drew wrote, via // NOLINT.
73,283,965
73,284,154
OOP Best Way To Call Similar Functions
Background: I have 2 similar blocks of code that I would like to merge together in a function. One block is for the x axis and the other is for the y axis. I have had this similar issue multiple times before and have shrugged it off since I assumed there was no better way of merging these in a clean fashion. Problem: How do I make a function that can replace both snippets of code below in the least number of lines? Code: //rows vector<float> rowSpectrum; float tempVal; for (int i = 0; i < ROI.size().height; i++) { tempVal = cv::mean(cleanImg.row(i)).val[0]; rowSpectrum.push_back(tempVal); } //columns vector<float> colSpectrum; for (int i = 0; i < ROI.size().width; i++) { tempVal = cv::mean(cleanImg.col(i)).val[0]; colSpectrum.push_back(tempVal); }
auto calcSpectrum = [&](int size, cv::Mat (cv::Mat::*memFn)(int) const) { vector<float> spectrum; for (int i = 0; i < size; i++) { auto tempVal = cv::mean((cleanImg.*memFn)(i)).val[0]; spectrum.push_back(tempVal); } return spectrum; } auto rowSpectrum = calcSpectrum(ROI.size().height, &cv::Mat::row); auto colSpectrum = calcSpectrum(ROI.size().width, &cv::Mat::col);
73,284,075
73,284,891
Cap'n proto link error undefined symbol capnp::MessageBuilder::getRootInternal() arm
i am trying to build and link cap'n proto library using arm-linux-gnueabihf-ld and receive such link errors. also i am building it on docker and snapcraft. arm-linux-gnueabihf-ld: error: undefined symbol: capnp::MessageBuilder::getRootInternal() >>> referenced by main.cpp >>> CMakeFiles/feature-manager.dir/src/main.cpp.o:(SysRegRequestBuilder::buildVersion(capnp::MallocMessageBuilder&, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)) >>> referenced by main.cpp >>> CMakeFiles/feature-manager.dir/src/main.cpp.o:(SysRegRequestBuilder::buildAuth(capnp::MallocMessageBuilder&, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)) >>> referenced by main.cpp >>> CMakeFiles/feature-manager.dir/src/main.cpp.o:(SysRegRequestBuilder::buildGet(capnp::MallocMessageBuilder&, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)) >>> referenced 10 more times arm-linux-gnueabihf-ld: error: undefined symbol: capnp::_::PointerBuilder::initStruct(capnp::_::StructSize) >>> referenced by main.cpp >>> CMakeFiles/feature-manager.dir/src/main.cpp.o:(SysRegRequestBuilder::buildVersion(capnp::MallocMessageBuilder&, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)) >>> referenced by main.cpp >>> CMakeFiles/feature-manager.dir/src/main.cpp.o:(SysRegRequestBuilder::buildVersion(capnp::MallocMessageBuilder&, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)) >>> referenced by main.cpp >>> CMakeFiles/feature-manager.dir/src/main.cpp.o:(SysRegRequestBuilder::buildAuth(capnp::MallocMessageBuilder&, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)) >>> referenced 23 more times arm-linux-gnueabihf-ld: error: undefined symbol: void capnp::_::PointerBuilder::setBlob<capnp::Text>(capnp::Text::Reader) >>> referenced by main.cpp >>> CMakeFiles/feature-manager.dir/src/main.cpp.o:(SysRegRequestBuilder::buildVersion(capnp::MallocMessageBuilder&, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)) >>> referenced by main.cpp >>> CMakeFiles/feature-manager.dir/src/main.cpp.o:(SysRegRequestBuilder::buildAuth(capnp::MallocMessageBuilder&, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)) >>> referenced by main.cpp >>> CMakeFiles/feature-manager.dir/src/main.cpp.o:(SysRegRequestBuilder::buildGet(capnp::MallocMessageBuilder&, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)) >>> referenced 12 more times arm-linux-gnueabihf-ld: error: undefined symbol: capnp::_::ListBuilder::asReader() const >>> referenced by main.cpp >>> CMakeFiles/feature-manager.dir/src/main.cpp.o:(SysRegResponseBuilder::buildEnumerate(capnp::MallocMessageBuilder&, capnp::List<capnp::Text, (capnp::Kind)1>::Builder const&, capnp::schemas::SysregStatus_b56039029f3859aa)) arm-linux-gnueabihf-ld: error: undefined symbol: capnp::_::PointerBuilder::setList(capnp::_::ListReader const&, bool) >>> referenced by main.cpp >>> CMakeFiles/feature-manager.dir/src/main.cpp.o:(SysRegResponseBuilder::buildEnumerate(capnp::MallocMessageBuilder&, capnp::List<capnp::Text, (capnp::Kind)1>::Builder const&, capnp::schemas::SysregStatus_b56039029f3859aa)) clang-11: error: linker command failed with exit code 1 (use -v to see invocation) make[2]: *** [CMakeFiles/feature-manager.dir/build.make:145: feature-manager] Error 1 make[1]: *** [CMakeFiles/Makefile2:83: CMakeFiles/feature-manager.dir/all] Error 2 make: *** [Makefile:136: all] Error 2
You need to link your binary against the libcapnp.so or libcapnp.a library. If you've installed the libraries to your system then the linker flag -lcapnp should accomplish this.
73,284,214
73,284,379
error: conversion from ‘unique_ptr<GreenStack,default_delete<GreenStack>>’ to non-scalar type ‘unique_ptr<Stack,default_delete<Stack>>’ requested
I am trying to assign a unique_ptr holding a derived class pointer to a unique_ptr holding a base class pointer. However, I am receiving the following error: error: conversion from ‘unique_ptr<GreenStack,default_delete<GreenStack>>’ to non-scalar type ‘unique_ptr<Stack,default_delete<Stack>>’ requested Code snippet is below. class GreenStack; class Stack { public: explicit Stack(double initial_weight) : weight_(initial_weight) {} static std::unique_ptr<Stack> makeGreenStack(double initial_weight) { //std::unique_ptr<Stack> box = std::make_unique<Stack>(initial_weight); std::unique_ptr<Stack> green_box_01 = std::make_unique<GreenStack>(initial_weight); return std::move(green_box_01); } bool operator<(const Stack& rhs) const { return weight_ < rhs.weight_; } virtual ~Stack() = default; protected: double weight_; }; class GreenStack:public Stack { public: explicit GreenStack(double initial_weight): Stack(initial_weight){} ~GreenStack() = default; }; Please guide to resolve this error.
Define Stack::makeGreenStack(double) after defining GreenStack to be derived from Stack. The compiler will then know that a std::unique_ptr<Stack> can be initialized from a std::unique_ptr<GreenStack> class GreenStack; class Stack { public: explicit Stack(double initial_weight) : weight_(initial_weight) {} static std::unique_ptr<Stack> makeGreenStack(double initial_weight); bool operator<(const Stack& rhs) const { return weight_ < rhs.weight_; } virtual ~Stack() = default; protected: double weight_; }; class GreenStack:public Stack { public: explicit GreenStack(double initial_weight): Stack(initial_weight){} ~GreenStack() = default; }; std::unique_ptr<Stack> Stack::makeGreenStack(double initial_weight) { std::unique_ptr<Stack> green_box_01 = std::make_unique<GreenStack>(initial_weight); return green_box_01; }
73,284,661
73,284,819
Pushing values in merge sort array
Im tring to learn basic data structures & algorithms. I have a problem with merging two sorted doubly linked lists.I have no idea why the last value doesnt push to merged list. As results for now for my code i get this. Left List: [(1)(3)(5)] Right List: [(-1)(2)(10)(20)] Merged: [(-1)(1)(2)(3)(5)(10)] Expected: [(-1)(1)(2)(3)(5)(10)(20)] template <typename T> LinkedList<T> LinkedList<T>::merge(const LinkedList<T> &other) const { LinkedList<T> left = *this; LinkedList<T> right = other; LinkedList<T> merged; Node * lptr = left.head_; Node * rptr = right.head_; while (lptr != NULL && rptr !=NULL) { if(lptr->data <= rptr->data){ merged.pushBack(lptr->data); lptr = lptr->next; }else{ merged.pushBack(rptr->data); rptr = rptr->next; } if(lptr == NULL && rptr != NULL){ merged.pushBack(rptr->data); rptr = rptr->next; }else{ merged.pushBack(lptr->data); lptr = lptr->next; } } return merged; }
For these lists Left List: [(1)(3)(5)] Right List: [(-1)(2)(10)(20)] when the left list achieves a null pointer the right list yet contains two nodes with values 10 and 20. However you are appending only one node if(lptr == NULL && rptr != NULL){ merged.pushBack(rptr->data); rptr = rptr->next; }else{ if(lptr == NULL && rptr != NULL){ //.. Also pay attention to that the negation of the condition lptr == NULL && rptr != NULL looks like !( lptr == NULL && rptr != NULL ) that is the same as ( lptr != NULL || rptr == NULL ) So you may not use in this if statement just the else part. Remove this code snippet from the while loop and write two additional while loops like while (lptr != NULL && rptr !=NULL) { if(lptr->data <= rptr->data){ merged.pushBack(lptr->data); lptr = lptr->next; }else{ merged.pushBack(rptr->data); rptr = rptr->next; } } while (lptr != NULL ){ merged.pushBack(lptr->data); lptr = lptr->next; } while (rptr != NULL ){ merged.pushBack(rptr->data); rptr = rptr->next; } There is also one more drawback. In these records LinkedList<T> left = *this; LinkedList<T> right = other; there is used the copy constructor that can results either in undefined behavior or in creating new lists that is inefficient. So remove these records and just write Node * lptr = this->head_; Node * rptr = other.head_; So the function will look like template <typename T> LinkedList<T> LinkedList<T>::merge(const LinkedList<T> &other) const { LinkedList<T> merged; Node * lptr = this->head_; Node * rptr = other.head_; while (lptr != NULL && rptr !=NULL) { if(lptr->data <= rptr->data){ merged.pushBack(lptr->data); lptr = lptr->next; }else{ merged.pushBack(rptr->data); rptr = rptr->next; } } while ( lptr != NULL ){ merged.pushBack(lptr->data); lptr = lptr->next; } while ( rptr != NULL ){ merged.pushBack(rptr->data); rptr = rptr->next; } return merged; }
73,284,766
73,327,425
std::system::error exception during recursive_directory_iterator | Unicode Translation Exception 1113 in C++
I was working on a bigger project using the recursive_directory_iterator of std::filesystem, when I stumbled upon this seemingly unknown/unfixable error. I simplified the project to the bare minimum to recreate the error. Another questioner found a solution in providing the skip_permission_denied option, which does nothing for me. The exception is not limited to this file, it happens for random other files too, if I delete this one, for instance. Though it occurs for the same file every time if I decide not to delete it. If I use the continue button on Visual Studio three times, it is actually able to continue the traversal of files. What would be a proper way to address this error? And what could potentially cause this? I removed all exception handling for readability, but the error occurs at the start of the for loop once it reaches this file. #define NOMINMAX #include <string> #include <iostream> #include <filesystem> #include <windows.h> #include <fstream> #include <winbase.h> #include <numeric> #include <string_view> #include <vector> #include <shlobj_core.h> //#include <combaseapi.h> namespace fs = std::filesystem; using namespace std; void startWinXSearch(string argv) { string pathToFolder = argv; cout << pathToFolder << endl; for (auto& el : std::filesystem::recursive_directory_iterator(pathToFolder, std::filesystem::directory_options::skip_permission_denied)) { cout << el << endl; } } int main(int argc, char* argv[]) { CoInitializeEx(NULL, COINIT_MULTITHREADED); string test = "C:\\Sciebo"; startWinXSearch(test); } UPDATE: This is what I get from using wcout. No idea what this is supposed to mean. Is it that there's an invisible file there?! The Error thrown currently is No mapping for the Unicode character exists in the target multi-byte code page. If I find a solution or workaround I'll update it here. FINAL UPDATE: I got it. Take a look at one of the comments ^^ It originated from invisible Unicode characters infront of a random file from my phone :D I even got a fix/workaround for it!
SOOOOOOO I got the answer.. The problem originates from invisible (atleast for win10) unicode characters infront of a file ^^ How do you prevent that from crashing your programm? EZ, we first build our iterating for loop. EG like this: for (auto& dirEntry : fs::recursive_directory_iterator(pathToFolder)) // Iterates over every file/folder in the path of the executable and its subdiretories { const std::wstring currentPath = dirEntry.path().c_str(); string output = wide_string_to_string(currentPath); std::cout << output << endl; } Then we require a suited and well done wstring -> string conversion ^^ I got this one from some site I just can't find again.. std::string wide_string_to_string(const std::wstring& wide_string) { if (wide_string.empty()) { return ""; } const auto size_needed = WideCharToMultiByte(CP_UTF8, 0, &wide_string.at(0), (int)wide_string.size(), nullptr, 0, nullptr, nullptr); if (size_needed <= 0) { throw std::runtime_error("WideCharToMultiByte() failed: " + std::to_string(size_needed)); } std::string result(size_needed, 0); WideCharToMultiByte(CP_UTF8, 0, &wide_string.at(0), (int)wide_string.size(), &result.at(0), size_needed, nullptr, nullptr); return result; } Our Main would look something like this. int main() { CoInitializeEx(NULL, COINIT_MULTITHREADED); startWinXSearch("C:\\Users\\wwwgi\\OneDrive\\Dokumente\\test"); CoUninitialize(); } Ofc you can also work with argv values, you just gotta format the raw path the appropiate way ^^ you can even use wmain + wchar_t argv[] if you like that! If you are unsure about the formatting you can try to format it with .path() and .string()/.c_string() :)
73,284,775
73,284,853
could not convert from ‘<brace-enclosed initializer list>’ to map
my code is as bellow: class A{ private: size_t linearProbing(T k, size_t i); size_t quadraticProbing(T k, size_t i); size_t doubleHashing(T k, size_t i); std::map<std::string, size_t (*)(T, size_t)> probeFunctionMap = { {"linearProbing", this->linearProbing}, {"quadraticProbing", this->quadraticProbing}, {"doubleHashing", this->doubleHashing} }; } And the error is: error: could not convert '{{"linearProbing", ((HashTableOpeningAddress<int>*)this)->HashTableOpeningAddress<int>::linearProbing}, {"quadraticProbing", ((HashTableOpeningAddress<int>*)this)->HashTableOpeningAddress<int>::quadraticProbing}, {"doubleHashing", ((HashTableOpeningAddress<int>*)this)->HashTableOpeningAddress<int>::doubleHashing}}' from '<brace-enclosed initializer list>' to 'std::map<std::__cxx11::basic_string<char>, long unsigned int (*)(int, long unsigned int), std::less<std::__cxx11::basic_string<char> >, std::allocator<std::pair<const std::__cxx11::basic_string<char>, long unsigned int (*)(int, long unsigned int)> > >' I guess the method I used to init the map is wrong, but I don't know how to correct it.
A function pointer cannot store the state that you care about (aka this). You need to be able to store this state so that you can call using this later when you use this map. An example might be: std::map<std::string, std::function<size_t(T, size_t)>> The std::function will let you store the state. But you cannot create a std::function with this->function_name. That is close to calling the function. So you have 2 options: std::bind - hard lambda - easy So lets look at a lambda. An example would be: [this](T k, size_t i) { return functor(k, i); } ^ Capture our state, aka `this` ^ take the same arguments as the function we care about ^ Call the function we care about We can set up a bunch of these lambdas (using a macro for ease): #define AS_FUNCTOR(functor) [this](T k, size_t i) { return functor(k, i); } std::map<std::string, std::function<size_t(T, size_t)>> probeFunctionMap = { {"linearProbing", AS_FUNCTOR(linearProbing)}, {"quadraticProbing", AS_FUNCTOR(quadraticProbing)}, {"doubleHashing", AS_FUNCTOR(doubleHashing)} This will make a map that we can use! Live example.
73,284,968
73,285,022
const struct object access member functions (and an operator overloading question)
I tried to overload the << operator for my custom struct, but encountered error C2662, code as follows: struct HP{ int max_hp; int hp; HP(int max_hp){ this->max_hp=max_hp; this->hp=max_hp; } // this const declarative doesn't support const HP& obj argument const string repr(){ stringstream hp_stats; hp_stats << this->hp << "/" << this->max_hp; return hp_stats.str(); } // This is fine with const HP& obj argument const string repr(){ stringstream hp_stats; hp_stats << this->hp << "/" << this->max_hp; return hp_stats.str(); } }; // would cause error C2662 ostream& operator<<(ostream& out, const HP& obj){ out<<obj.repr(); return out; } I've found that this is because the implicitly access of this pointer, and const attempts to convert *this into const *this and thus fails. But as I changed from const string repr() to string repr() const, it magically worked and compiled successfully. What's the difference between a const T func(){} and T func() const, which makes a const struct object invoking feasible? I read it on cppreference.com, but still unsure why << overloading has to be declared outside a class scope. Suppose I have repr() member function for struct HP, struct Shield, etc. I tried to make the << overloading a template function, but it turns that I am overloading << at global scope. Can I specify the T I am about to apply, OR apply the overloading across several classes with same member function, WITHOUT classes defined under one base class? // complier thinks such overloading is global on << template <typename T> ostream& operator<<(ostream& out, const T& obj){ out<<obj.repr(); return out; }
const T func() {} means that the return type is const T and the function might mutate the object. Whereas, T func() const {} means that the return type is non-const but the object is unaltered (const). You can also have both or neither const. It doesn't have to be declared outside the class, it can be declared inside as a friend (non-member) function. That works here as well. However, for a member function: since operator<<()'s first parameter is ostream&, you could only declare it in ostream and not HP, which won't work. Remember, member operators are like *this as the first argument of non-member operators. Yes, you can do this. The easiest is to delegate to a common print function; the more elegant way is to use std::enable_if, e.g.: template <typename T> std::enable_if_v<std::is_same_v<T, HP> || std::is_same_v<t, Shield>, ostream&> operator<<(ostream& out, const T& obj) { out<<obj.repr(); return out; } You can also write the conditions as a template and then re-use it: template<typename T> static constexpr bool is_printable_v = std::is_same_v<T, HP> || std::is_same_v<T, Shield>; template <typename T> std::enable_if_v<is_printable_v<T>>, ostream&> operator<<(ostream& out, const T& obj) { ... }
73,284,992
73,285,084
Cannot call DLL function
I have been trying to call a DLL that simply displays a MessageBox. I am running into issues where the loader will not locate the function. When the program is running, nothing happens. Tried using user32.dll which I know works for sure. Everything went fine with the SwapMouseButton function. I have defined my imports and exports. Perhaps they were not done properly? Were my calling conversions wrong? Here are my imports and exports: #ifndef INDLL_H #define INDLL_H #ifdef EXPORTING_DLL extern __declspec(dllexport) void HelloWorld(); #else extern __declspec(dllimport) void HelloWorld(); #endif #endif Hello World DLL (trying to display MessageBox from DLL loader): /* Hello World DLL */ #include "stdafx.h" #define EXPORTING_DLL #include "sampleDLL.h" #include "pch.h" BOOL APIENTRY DllMain(HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) { return TRUE; } void HelloWorld() { MessageBox(NULL, TEXT("Hello World"), TEXT("In a DLL"), MB_OK); } DLL Loader (could have wrong conversions): /* DLL Loader */ #include <windows.h> #include <iostream> typedef int(__stdcall* f_funci)(); int main() { HINSTANCE hGetProcIDDLL = LoadLibrary("PATH\\LoadME.dll"); if (!hGetProcIDDLL) { return EXIT_FAILURE; } // resolve function f_funci functon = (f_funci)GetProcAddress(hGetProcIDDLL, "HelloWorld"); if (!functon) { std::cout << "Function Could Not Be Located" << std::endl; return EXIT_FAILURE; } std::cout << "returned " << functon() << std::endl; return EXIT_SUCCESS; }
Your DLL function does not have a calling convention specified, so it will use the compiler's default, which is most likely __cdecl NOT __stdcall. But your EXE is defining f_funci to use __stdcall. So, even if the function could be found, it likely won't be called correctly. Double-check the function's name mangling in the DLL's exports table. It i likely being exported as "_HelloWorld" instead of "HelloWorld". Consider using a .DEF file when compiling the DLL in order to control how the function is exported. Also, consider wrapping the function's declaration in extern "C" when compiling in C++.
73,285,120
73,285,597
C++ VS Code not recognizing syntax, unable to run code
I am using a specific syntax needed for a course, but when I use this C++ syntax in VS Code, it doesn't work and raises errors. Here is an example of the syntax that is not working: error: expected ';' at end of declaration int i {0}; ^ ; When I change it to int i = 0; the error disappears. It specifically doesn't recognize the {} syntax for setting default variable values. I am using a ssh login for this course and the syntax works well in the ssh, but won't work in VS Code. I attempted to change my VS Code C++ version to C++17 by doing the top answer in this thread, but it still doesn't recognize the syntax. Am I using incorrect syntax, or is there a way to fix this?
Adding on to the comment above, this is what solved my issue: Go to this link: https://code.visualstudio.com/docs/cpp/config-clang-mac Go to the section Clang on macOS and scroll down to Troubleshooting. Follow the steps in this paragraph: "If you see build errors mentioning "C++11 extensions", you may not have updated your tasks.json build task to use the clang++ argument --std=c++17. By default, clang++ uses the C++98 standard, which doesn't support the initialization used in helloworld.cpp. Make sure to replace the entire contents of your tasks.json file with the code block provided in the Run helloworld.cpp section." You will need to copy-paste this exact code and replace the code in the tasks.json folder: { // See https://go.microsoft.com/fwlink/?LinkId=733558 // for the documentation about the tasks.json format "version": "2.0.0", "tasks": [ { "type": "shell", "label": "C/C++: clang++ build active file", "command": "/usr/bin/clang++", "args": [ "-std=c++17", "-stdlib=libc++", "-g", "${file}", "-o", "${fileDirname}/${fileBasenameNoExtension}" ], "options": { "cwd": "${workspaceFolder}" }, "problemMatcher": ["$gcc"], "group": { "kind": "build", "isDefault": true }, "detail": "Task generated by Debugger." } ] } To find the tasks.json folder, go to your program-file, do Command + Shift + . to find hidden files > .vscode > tasks.json > replace all the code in the file with the one I provided. It updates the C++ compiler to use a more updated version of C++ which recognizes the syntax.
73,286,081
73,287,778
CMake command line define macro without value
I have the following line in my CMakeLists.txt add_compile_definitions(DEBUG=$(DEBUG)) so when I compile my code with Makefile, I can do this make DEBUG=1 But what I really want is to just define the DEBUG macro without setting any value to it. Is there a way I can do this on a command line with cmake?
With CMake you can, at configuration time, add some CMake variables. For example you can do this cmake -S <src_folder> -B <build_folder> -DDEBUG=ON. This way you will have access to the variable DEBUG in your CMake. In your CMake you will have this code if(DEBUG) add_compile_definition(DEBUG) endif() (Note that instead of add_compile_definitions, it is recommended to use target_compile_definitions which will set your DEBUG macro only for one target and not globally to your project. Example: add_executable(my_target main.cpp) target_compile_definition(my_target PRIVATE DEBUG) PRIVATE means that this compile_definition will only be used by the target my_target and will not be propagated to others.) But if you're only concern of the building type, I suggest that you use CMake variables that are already present within CMake. You can use CMAKE_BUILD_TYPE which will contains Debug, Release or whatever depending on what type of build you want. Your code will now be this if("${CMAKE_BUILD_TYPE}" STREQUAL "Debug") add_compile_definition(DEBUG) endif() And you can use this command line cmake -S <src_folder> -B <build_folder> -DCMAKE_BUILD_TYPE=Debug And here the documentation https://cmake.org/cmake/help/latest/variable/CMAKE_BUILD_TYPE.html?highlight=cmake_build_type Note that this solution will only works for Mono-config generators like Makefile or Ninja and will not works with Visual Studio or Xcode
73,286,101
73,289,770
pybind11 STL autoconverter breaks std::list pointers
I have a C++ library that manipulates (among other things) a list of wrappers that I have been working on converting to Python using pybind11. The rest of the library operates on a pointer to a list of pointers: std::list<Symbol*>*. The problem is that when attempting to autocast a Python list to this C++ list and then initializing a ParamMap, an object that holds the list on the C++ side, the pointers of the list get all messed up. Inspection in GDB reveals that the "next-object pointers" of all the objects are invalid, and this leads to segfaults when traversing the list. There is no sign of the objects being deallocated on the C++ side, as neither the destructors for the list container ParamMap nor the list objects Symbol are called. I've deduced that the issue might be Python hyperactively deleting objects C++ is still using, but I've tried object terms like py::return_value_policy::reference and py::keep_alive, and they haven't fixed the problem. What is going wrong here? Unfortunately, changing the list type on the C++ side is not an option, but I would really appreciate some help in making this work on the Python side. Thank you! Here is some minimal reproduction code: Symbol.hpp #include <string> class Symbol { private: std::string val1; int val2; public: Symbol(std::string con1, int con2) : val1(con1), val2(con2) {} }; ParamMap.hpp #include <list> #include "Symbol.hpp" class ParamMap { private: std::list<Symbol*>* lst; int otherData; public: ParamMap(std::list<Symbol*>* symbolList, int dat) : lst(symbolList), otherData(dat) {} std::list<Symbol*>* getSymbols() { return lst; } int getOtherData() { return otherData; } }; Query.cpp #include <iostream> #include "ParamMap.hpp" #include <pybind11/pybind11.h> #include <pybind11/stl.h> namespace py = pybind11; void getSymbolListSize(ParamMap* map) { std::cout << "Entering query method" << std::endl; auto sz = map->getSymbols()->size(); // SEGFAULT OCCURS WHEN GETTING SIZE std::cout << "Got size successfully. Size = " << sz << std::endl; } PYBIND11_MODULE(list_test, handle) { handle.def("getSymbolListSize", &getSymbolListSize); py::class_<ParamMap>(handle, "ParamMap") .def(py::init<std::list<Symbol*>*, int>(), py::keep_alive<1, 2>()) .def("getOtherData", &ParamMap::getOtherData) .def("getSymbols", &ParamMap::getSymbols); py::class_<Symbol>(handle, "Symbol") .def(py::init<std::string, int>()); } test.py import list_test as p # Creating a list of some random symbols symbol_list = [] symbol1 = p.Symbol("Hello", 1) symbol_list.append(symbol1) symbol2 = p.Symbol("World", 2) symbol_list.append(symbol2) # Creating a parammap and passing it the symbol list pm = p.ParamMap(symbol_list, 71) print("Symbol list and ParamMap init'd successfully") # Here, calling Query.cpp's only method sz = p.getSymbolListSize(pm) print(sz)
I don't know a lot about how pybind11 works its magic and therefore I can't help you understanding what is going on. However, I have the feeling that pybind attempts to build the list even though your code only uses a pointer to the list. If I were you I'd consider this a pybind bug and post it as an issue on their github page. As per your code, doing something like this seems to work (although it's not very clean): #include <list> #include "Symbol.hpp" class ParamMap { private: std::list<Symbol*>* lst; int otherData; public: ParamMap(std::list<Symbol*> *symbolList, int dat) : lst(symbolList), otherData(dat) { lst = new std::list<Symbol *>; for(auto s : *symbolList) { lst->push_back(s); } } ~ParamMap() { delete lst; } std::list<Symbol*>* getSymbols() { return lst; } int getOtherData() { return otherData; } }; I don't know who's supposed to manage the lifetime of the pointed list, so you may want to remove the destructor in case someone else is supposed to deallocate the list.
73,286,188
73,286,474
Can a C++ function return without explicit giving type instantiation / with empty initializer list
Assuming a function with complicated return type, can we simplify the return statement?(no need to specify detailed return type) std::vector<std::map<int/*id*/, std::string/*data*/>> GetSomeData(int type) { if (type == DataType::Invalid) { return std::vector<std::map<int, std::string>>(); // this works return {}; // can we make this happen? } } I know there is another way doing that: std::vector<std::map<int/*id*/, std::string/*data*/>> GetSomeData(int type) { std::vector<std::map<int, std::string>> ret; if (type == DataType::TypeA) { .... // filling ret here } else if (....) { .... } return ret; } But I'm still curious about this question.
Yes, it can. {} can be used to initialize an empty std::vector<?>. This code can be compiled in gcc (Ubuntu 9.4.0-1ubuntu1~20.04.1) 9.4.0 with command g++ -o cpp-lab -std=c++11 main.cpp: #include <iostream> #include <vector> #include <map> #include <string> std::vector<std::map<int, std::string>> GetSomeData(int type) { return {}; } // ... main function declaration ...
73,286,205
73,309,655
How to use Crow on Raspberry Pi
I'm trying to start a webserver using a Raspberry Pi for listening to POST requests from IFTTT. I'm programming in C++. I first tried Crow, which wouldn't work at all, giving the error "Handler function cannot have void return type...". I saw that others had also had issues with it, so I looked for a new solution. I found RestINIO, which looks great, but I can't figure out how to install it on my Raspberry PI. I looked at the docs, but couldn't figure out how to get it to install. I know this probably isn't the right place for this, but any help would be much appreciated!
Here's what I had to do (simple fix): In Geany: Go to Build > Set Build Commands Under both "compile" and "build", add the following text to the end of the string: -lboost_system Compilation is successful!
73,286,560
73,286,640
can anyone explain why my code gets runtime error in cpp?
Can anyone solve this runtime error? Status :Time limit exceeded Time: 5 secs Memory: 5.368 Mb Input 4 8 4 1 2 1 2 5 3 5 1 3 4 1 2 4 5 11 1 1 1 3 12 Runtime Error SIGTSTP #include <iostream> using namespace std; int main() { // your code goes here int n,m,k,cert=0; cin>>n>>m>>k; int a; for(int z=0;z<n;z++) { int sum=0; for(int i=0;i<k;k++) { cin>>a; sum+=a; } cin>>a; if(sum>=m && a<=10) cert++; } cout<<cert; return 0; }
It's because your code runs for a very long time. Look at this loop: for (int i = 0; i < k; k++) { k will increase, while i stays at 0 so i < k will always be true. When k at some point reaches its limit, INT_MAX, and you do k++, it'll will cause signed integer overflow and the program therefore has undefined behavior. Without knowing what your code is supposed to do, it's not possible to give an exact advice how to make it work, but I suspect that you want this instead: for (int i = 0; i < k; i++) {
73,286,731
73,314,673
fgetc doesn't return to process
I'm trying to do something like echo {a:1} | prettier --stdin-filepath index.js and return the value returned in stdout. But I also want to make this program platform independant. Referencing this and this, I managed to write code like this: #include <Windows.h> #include <fcntl.h> #include <io.h> #include <iostream> #include <stdexcept> HANDLE hChildStd_IN_Rd = NULL; HANDLE hChildStd_IN_Wr = NULL; HANDLE hChildStd_OUT_Rd = NULL; HANDLE hChildStd_OUT_Wr = NULL; int main() { const char source_code[] = "{a:1}"; FILE *fd_OUT = nullptr, *fd_IN = nullptr; #ifdef _WIN32 try { SECURITY_ATTRIBUTES saAttr{}; saAttr.nLength = sizeof(SECURITY_ATTRIBUTES); saAttr.bInheritHandle = TRUE; saAttr.lpSecurityDescriptor = NULL; if (!CreatePipe(&hChildStd_OUT_Rd, &hChildStd_OUT_Wr, &saAttr, 0)) throw std::runtime_error("StdoutRd CreatePipe"); if (!SetHandleInformation(hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)) throw std::runtime_error("Stdout SetHandleInformation"); if (!CreatePipe(&hChildStd_IN_Rd, &hChildStd_IN_Wr, &saAttr, 0)) throw std::runtime_error("Stdin CreatePipe"); if (!SetHandleInformation(hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0)) throw std::runtime_error("Stdin SetHandleInformation"); TCHAR szCmdline[] = TEXT( "C:\\Users\\yuto0214w\\AppData\\Roaming\\npm\\prettier.cmd " "--stdin-filepath index.js"); PROCESS_INFORMATION piProcInfo; STARTUPINFO siStartInfo; ZeroMemory(&piProcInfo, sizeof(PROCESS_INFORMATION)); ZeroMemory(&siStartInfo, sizeof(STARTUPINFO)); siStartInfo.cb = sizeof(STARTUPINFO); siStartInfo.hStdError = hChildStd_OUT_Wr; siStartInfo.hStdOutput = hChildStd_OUT_Wr; siStartInfo.hStdInput = hChildStd_IN_Rd; siStartInfo.dwFlags |= STARTF_USESTDHANDLES; if (!CreateProcess(NULL, szCmdline, NULL, NULL, TRUE, 0, NULL, NULL, &siStartInfo, &piProcInfo)) throw std::runtime_error("CreateProcess"); CloseHandle(piProcInfo.hProcess); CloseHandle(piProcInfo.hThread); CloseHandle(hChildStd_OUT_Wr); CloseHandle(hChildStd_IN_Rd); fd_OUT = _fdopen(_open_osfhandle((intptr_t)hChildStd_OUT_Rd, _O_RDONLY), "r"); fd_IN = _fdopen(_open_osfhandle((intptr_t)hChildStd_IN_Wr, _O_WRONLY), "w"); } catch (std::exception& e) { std::cout << std::string("Encountered an error when running: ") + e.what() << std::endl; return 1; } #else // pipe fork dup2 execlp fdopen #endif fputs(source_code, fd_IN); std::string formatted_code; int c; while ((c = fgetc(fd_OUT)) != EOF) { formatted_code += c; std::cout << "ch: " << c << std::endl; // For testing } fclose(fd_OUT); fclose(fd_IN); std::cout << formatted_code << std::endl; return 0; } This will compile, but stops completely on fgetc. I mean stops completely by it doesn't show any ch:. I built program using MSVC v143. Thanks
The problem was I wasn't closing fd_IN before reading fd_OUT. This causes deadlock because prettier is awaiting input from program, and program is awaiting output from prettier. To fix this, fputs(source_code, fd_IN); fclose(fd_IN); std::string formatted_code; int c; while ((c = fgetc(fd_OUT)) != EOF) { formatted_code += c; std::cout << "ch: " << c << std::endl; // For testing } fclose(fd_OUT);
73,287,968
73,288,013
I don't understand why my sort on a string breaks everything
I have the following code: #include <algorithm> #include <iostream> #include <string> #include <vector> #include <unordered_map> using namespace std; vector<vector<string>> findAnagrams(vector<string> wordlist) { vector<vector<string>> result; unordered_map<string, vector<string>*> indexes; for (const string& word : wordlist) { string wordSorted = word; sort(wordSorted.begin(), wordSorted.end()); // <= This line break everything auto index = indexes.find(wordSorted); if (index == indexes.end()) { vector<string> vec = { word }; result.push_back(vec); indexes[wordSorted] = &vec; } else { index->second->push_back(word); } } return result; } int main() { vector<string> wordlist = {"eat", "tea", "tan", "ate", "nat", "bat", "test", "estt"}; auto result = findAnagrams(wordlist); for (const auto& vec : result) { for (const auto& word : vec) { cout << word << " "; } cout << endl; } return 0; } This code detects all anagrams in a list of given words. As my comment says, when I sort wordSorted using std::sort, it breaks everything and my code ends with a bad_alloc. As if the std::sort manipulates the memory outside of wordSorted. If I remove this specific line, the code "works" (the result is obviously wrong, but it does what it should do). How it is possible? What am I missing?
I'm guessing these lines are the main cause of your problem: { vector<string> vec = { word }; result.push_back(vec); indexes[wordSorted] = &vec; } Here you store a pointer to the local variable vec in the indexes map. When the block ends at } the life-time of vec also ends, and the pointer you just stored will become invalid. Any use of this pointer will lead to undefined behavior. It seems to me that the solution is to simply not store pointers to the vector (pointers to containers are seldom, if ever, needed), and instead store a copy.
73,288,009
73,289,096
How to feed multiple input into opencv dnn
I have a .pb model file. And I loaded the model using opencv's readnetfromtensorflow(). Now I want to use the model to generate predictions. There are 4 types of model input. Input data 256x256 image 64x64 image 64x64 image array (size is 4) output data array (size is 2) To generate the model's predictions, I first had to transform the input into blobFromImages. However, I couldn't use it because each image that needs to be converted has a different size. I also tried inserting each image into a vector in setInput() but it failed. What should I do when there are multiple inputs in this situation? Here is the code I've tried. cv::dnn::Net net = cv::dnn::readNetFromTensorflow("model/mfg.pb”); cv::Mat input_face = cv::dnn::blobFromImage(face, 1, cv::Size(256,256), cv::Scalar(104,177,123), true, false); cv::Mat input_leye = cv::dnn::blobFromImage(leye, 1, cv::Size(64,64), cv::Scalar(104,177,123), true, false); cv::Mat input_reye = cv::dnn::blobFromImage(reye, 1, cv::Size(64,64), cv::Scalar(104,177,123), true, false); cv::Mat input_bbox = (cv::Mat1d(1,4) << face_bbox[0]., face_bbox[1]., face_bbox[2]., face_bbox[3].); std::vector<cv::Mat> input_image = {input_face, input_leye, input_reye, input_bbox}; net.setInput(input_image); net.forward(); However, it failed and an error message appeared. Error libc++abi: terminating with uncaught exception of type cv::Exception: OpenCV(4.5.5) /tmp/opencv-20220714-27380-1eyun69/opencv-4.5.5/modules/core/src/matrix_wrap.cpp:81: error: (-215:Assertion failed) 0 <= i && i < (int)v.size() in function 'getMat_'
You can't set multiple inputs on a cv::dnn::Net.(It's not supported.) I suggest two alternatives. You do that DNN calculations with Tensorflow and other image/video tasks with OpenCV. You can wrap the data of a tensorflow::Tensor as a cv::Mat. (See Guillaume's answer in this question.) Redesign the functional model into a sequential model.
73,288,015
73,288,059
What was the idiomatic way of reverse traversal of an iterable before C++11?
void rev(string& str) { for (auto i = str.end() -1; i != str.begin() -1; i--) cout << *i; cout << '\n'; } The code above works on my system however str.begin() -1 invokes undefined behaviour as per the standard. So what is the idiomatic way of reverse traversal using iterator's but not reverse_iterator's?
This works for (auto i = str.end(); i != str.begin(); ) { --i; ... }
73,288,713
73,302,085
How to fetch RSA public key modulus and exponent in C/C++?
I'm using the BCrypt Windows library to handle the RSA algorithm in my application. Problem : I need to fetch the RSA public key modulus and exponent. In C# language, I was using the RSACryptoProvider class to fetch these informations (ExportParameters method). In my C/C++ application, BCrypt seems to be unable to fetch the right data... What I've done so far: BOOL RSA_New(RSA_CTX_ST* rsa_ctx, const BYTE key_data[256], DWORD key_len, BOOL cipher) { if (rsa_ctx == NULL || key_len != RSA_2048_BLOCK_SIZE) { return FALSE; } NTSTATUS status = STATUS_UNSUCCESSFUL; BCRYPT_ALG_HANDLE* algo_handle = NULL; BCRYPT_KEY_HANDLE* key_handle = NULL; algo_handle = malloc(sizeof(BCRYPT_ALG_HANDLE)); key_handle = malloc(sizeof(BCRYPT_KEY_HANDLE)); if (algo_handle == NULL || key_handle == NULL) goto END; //Creation handle Algo if (!NT_SUCCESS(status = BCryptOpenAlgorithmProvider(algo_handle, BCRYPT_RSA_ALGORITHM, NULL, 0))) { UTL_Trace("SEC", VRB_MAJOR, "RSA:Algorithm handle opening error"); if (status == STATUS_INVALID_HANDLE) { UTL_Trace("SEC", VRB_INFO, "INVALID HANDLE"); } if (status == STATUS_INVALID_PARAMETER) { UTL_Trace("SEC", VRB_INFO, "INVALID PARAMS"); } goto END; } // Key pair generation if (!NT_SUCCESS(status = BCryptGenerateKeyPair(algo_handle, key_handle, 2048, 0))) { UTL_Trace("SEC", VRB_MAJOR, "RSA:Key pair generating error"); if (status == STATUS_INVALID_HANDLE) { UTL_Trace("SEC", VRB_INFO, "INVALID HANDLE"); } if (status == STATUS_INVALID_PARAMETER) { UTL_Trace("SEC", VRB_INFO, "INVALID PARAMS"); } goto END; } BCRYPT_RSAKEY_BLOB my_rsa_blob; ULONG* pcbResult = NULL; pcbResult = calloc(1, sizeof(ULONG)); if (pcbResult == NULL) { UTL_Trace("SEC", VRB_INFO, "Allocating RSA result error"); goto END; } // Export parameters of keys if (!NT_SUCCESS(status = BCryptExportKey(key_handle, NULL, BCRYPT_RSAFULLPRIVATE_BLOB, &my_rsa_blob, sizeof(my_rsa_blob), pcbResult, 0))) { UTL_Trace("SEC", VRB_MAJOR, "RSA:Key pair exporting error"); if (status == STATUS_INVALID_HANDLE) { UTL_Trace("SEC", VRB_INFO, "INVALID HANDLE"); } if (status == STATUS_INVALID_PARAMETER) { UTL_Trace("SEC", VRB_INFO, "INVALID PARAMS"); } goto END; } return TRUE; END: if (algo_handle != NULL) free(algo_handle); if (key_handle != NULL) free(key_handle); return FALSE; } In my_rsa_blob, I should have the size of the modulus and exponent but not their values... Does anyone have a solution to this problem ?
In fact, I did find a solution ! With the call of BCryptExportKey, the variable my_rsa_blob should have been a PUCHAR variable, which is a pointer to a string. With this, I found a link in Microsoft Docs while searching... The link is showing how the PUCHAR variable is designed : https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-wcce/540b7b8b-2232-45c8-9d7c-af7a5d5218ed After, you can try to manipulate data like this : static BOOL RSA_RecoverKeyInformation(RSA_CTX_ST* rsa_ctx, PUCHAR ptrKey) { strncpy(rsa_ctx->key_information.header.Magic, ptrKey[0], 4); strncpy(rsa_ctx->key_information.header.BitLength, ptrKey[1 * 4], 4); strncpy(rsa_ctx->key_information.header.cbPublicExp, ptrKey[2 * 4], 4); strncpy(rsa_ctx->key_information.header.cbModulus, ptrKey[3 * 4], 4); strncpy(rsa_ctx->key_information.header.cbPrime1, ptrKey[4 * 4], 4); strncpy(rsa_ctx->key_information.header.cbPrime2, ptrKey[5 * 4], 4); size_t sizeOfModulus = rsa_ctx->key_information.header.cbModulus; size_t sizeOfExponent = rsa_ctx->key_information.header.cbPublicExp; rsa_ctx->key_information.keyExponent = malloc(sizeOfExponent); rsa_ctx->key_information.keyModulus = malloc(sizeOfModulus); if (rsa_ctx->key_information.keyExponent == NULL || rsa_ctx->key_information.keyModulus == NULL) goto END; strncpy(rsa_ctx->key_information.keyExponent, ptrKey[6 * 4], sizeOfExponent); strncpy(rsa_ctx->key_information.keyModulus, ptrKey[6 * 4 + sizeOfExponent], sizeOfModulus); return TRUE; END: if (rsa_ctx->key_information.keyExponent != NULL) free(rsa_ctx->key_information.keyExponent); if (rsa_ctx->key_information.keyModulus != NULL) free(rsa_ctx->key_information.keyModulus); return FALSE; }
73,288,758
73,288,966
How can I create dynamic array without asking user to enter a size in C++?
I want to take 8 char password from user and then when she/he wanted to enter, I wanted it to be whatever size she/he enter. However, the code doesn't stop until it reaches 8 char, even I press 'enter', it takes it as a char and create '*'. I want its size to be whatever user write and then user press 'enter', it will take these characters as password to see if it is matched with registered password. For example; User register password as 'wellcode' After that, user write in login screen 'well' then enter(in my code it lasts until I reach 8 characte 'Login failed! will be written Is there a way to do that in C++? bool CheckCredentials(string); char pass[8], inPass[8]; int main() { fstream encrypted; bool done = false; while (!done) { cout << "1. Register a password" << endl; cout << "2. Login your password" << endl; cout << "3. Exit" << endl; int menuChoice; cin >> menuChoice; if (menuChoice == 1) { ifstream ifile; ifile.open("password.txt"); if (ifile){} else { cout << "New password must contain only 8 characters: "; for (int i = 0; i < 8; i++) { pass[i] = _getch(); _putch('*'); } ofstream l("password.txt", ios::out); if (!l.is_open()) { cout << "could not open file \n"; } for (int i = 0; i < 8; i++) { l << pass[i]; } l.close(); cout << "\n\n"; } } else if (menuChoice == 2) { cout << "Password: "; for (int i = 0; i < 8; i++) { inPass[i] = _getch(); _putch('*'); } if (CheckCredentials(inPass) == true) { cout << "\nLogin sucessful!" << "\n\n"; } else { cout << "\nLogin failed!" } } else if (menuChoice == 3) { done = true; break; } } return 0; } bool CheckCredentials(string inPass) { string s; bool status = false; ifstream f; f.open("password.txt"); if (!f.is_open()) { cout << "Unable to open file!\n"; } else if (f) { while (!f.eof()) { f >> s; if (inPass == s) { status = true; } else { status = false; } } } f.close(); return status; }
Your code is for (int i = 0; i < 8; i++) { inPass[i] = _getch(); _putch('*'); } Obviously that loops exactly eight times, doesn't matter what you type. If you want to stop the loop early then you must write the code to test for that possibility. Something like int inPassLength = 0; for (int i = 0; i < 8; i++) { char ch = _getch(); if (ch == '\n') // quit loop if enter is pressed break; inPass[inPassLength++] = ch; putch('*'); } You also need to add a variable to record how long the password is (since it may not be exactly 8 characters any more) that's what inPassLength is in the code above.
73,289,715
73,291,534
Unpacking a tuple to call a function templated with variadic arguments in a subclass implementations (C++)
I am in the midst of implementing an Entity Component System. I am running into issues when attempting to call a function templated with variadic arguments: template <typename... Ts> struct engine_system : engine_system_base<Ts>... { using component_types = std::tuple<Ts...>; // subclass implements this virtual void process_values(float delta_time, Ts&... ts) const = 0; void update(float delta_time) const { auto component_view = registry.get_view<Ts...>(); for (component_types& c : component_view){ process_values(delta_time, ?????); // issue } } }; The engine_system_base takes care of registering T for each type in Ts. On update each system implementation is supposed to retrieve all necessary components from the registry. I am unfortunately not sure how I can unpack the component_types instance to correctly call a subclass implementation. Here is a full example (registry omitted): // components are just "plain old data" struct vec3 { float x, y, z; }; struct transform_component { vec3 position, rotation, scale; }; struct rigid_body_component { vec3 velocity, acceleration; }; Components store state and have no behavior. Systems implement behavior based on Components. // internal systems template <typename T> struct engine_system_base { engine_system_base() { /* register T for system in registry */ }; virtual ~engine_system_base() = default; }; template <typename... Ts> struct engine_system : engine_system_base<Ts>...{ using component_types = std::tuple<Ts...>; virtual void process_values(float delta_time, Ts&... ts) const = 0; void update(float delta_time) const { auto component_view = registry.get_view<Ts...>(); for (auto& c : component_view){ process_values(delta_time, ?????); // issue } } }; engine_system_base registers T for a subclass implementation. engine_system uses engine_system_base as a variadic base to register each T in Ts with the registry (omitted). Afterward, a system can be implemented as such: struct move_system : engine_system<transform_component, const rigid_body_component> { void process_values(float delta_time, transform_component& tc, const rigid_body_component& rb) const final { tc.position += rb.velocity * delta_time; } }; The move_system can then be used to translate all entities, which are comprised of a transform_component and rigid_body_component. int main() { move_system ms{}; ms.update(0.016); return 0; } In my first implementation, I defined void update(float delta_time) const individually for each system implementation, which works but duplicates the same exact implementation and only differs in by explicitly defining Ts... for each subclass. Unfortunately, I am running into the aforementioned issue when attempting to refactor this logic into engine_system.
Assuming component_view type is component_types, std::apply might help: void update(float delta_time) const { auto component_view = registry.get_view<Ts...>(); for (auto& c : component_view){ std::apply([&](auto&... args){ process_values(delta_time, args...); }, c); } }
73,290,108
73,290,317
C++ constructor call non-virtual function, let's say funcA, but funcA calls a virtual function, is it dangerous
I know we better don't call a virtual function in the constructor since the derived class construction not started yet based on https://isocpp.org/wiki/faq/strange-inheritance#calling-virtuals-from-ctors , but what's going on if we call a non-virtual function in constructor, but the non-virtual function call a virtual one, is it dangerous as well? If YES, then how can we avoid it, if the call stack for a non-virtual is more deep, we cannot be aware of this issue, right? class A { public: A() { funcA(); } void funcA() { func1(); } virtual void func1(){ std::cout << "A func1" <<std::endl; } }; class B : public A { public: B() { } virtual void func1(){ std::cout << "B func1" <<std::endl; } };
if we call a non-virtual function in constructor, but the non-virtual function call a virtual one, is it dangerous as well? Yes. Take this example: struct foo { foo() { proxy(); } void proxy() { call(); } virtual void call() = 0; }; struct bar : foo { void call() override {} }; Instantiating bar will most likely result in a runtime fault. It may print something like "pure virtual method called" and die. how can we avoid it, if the call stack for a non-virtual is more deep, we cannot be aware of this issue, right? Not without analysing the code. You may find a static analyzer that is capable of catching this - or you'll have to do it manually.
73,290,146
73,290,463
Vector passed by reference inside lambda cannot be modified even if mutable keyword is used
I am trying to populate a vector with integer values which are coming in from standard input as follows: std::vector<int> v; for_each(v.begin(),v.end(),([&](auto &i) mutable {cin>>i; v.push_back(i);})); However, this statement is not working and the vector does not get filled with incoming values. Can you please suggest where I am going wrong? Thanks
std::for_each applies the function object (the lambda) on each element in the passed container. Therefore to the parameter passed to the lambda is the current elements in the vector however, your vector is empty so there's nothing to iterate over so it never runs. You are also trying to assign the value from std::cin to the element in the vector i and then push a reference to that element again to the back of the vector along with the already existing element. So first of all, if you want to use std::for_each you need to pre-allocate the vectors memory so it has something to iterate over. std::vector<int> v(5); ///< allocates space for 5 ints You then can then run std::for_each and std::cin into the lambda's input parameter which is a iterator to the vector, saving the inputs to the vector. std::vector<int> v(5); std::for_each(v.begin(), v.end(), [](auto& i) { std::cin >> i; }); The benefit of this solution is that it will automatically terminate reading values once it has finished iterating through the vector, only reading the desired amount of values. Links and Resources std::for_each : cppreference
73,290,446
73,290,551
read file in docker volume from docker container
I have a docker image of the osrm-backend on github. When I start the container a profile.lua script is run, which triggers a .cpp file to read the content of the file rastersource.asc. The path of that file gets defined in the lua script. The C++ file inside the image is located in scr/extractor/rastersource.cpp, the profile.lua and rasterscource.asc are both in e:/docker so they should both be within the volume. What I do is I run the container with: docker run -t -v e:/docker:/data osrm/osrm-backend osrm-extract -p /data/profile.lua /data/location-latest.osm.pbf But now I struggle with defining the absolute path from which the rastersource.cpp should read the file. .lua code: raster_source = raster:load( os.getenv('file/path/which/is/unknown.asc'), 4.86, -- longitude min 5.5, -- longitude max 51.95, -- latitude min 52.286, -- latitude max 169, -- number of rows 321 -- number of cols ), .cpp code int RasterContainer::LoadRasterSource(const std::string &path_string, double xmin, double xmax, double ymin, double ymax, std::size_t nrows, std::size_t ncols) { ... boost::filesystem::path filepath(path_string); if (!boost::filesystem::exists(filepath)) { throw util::RuntimeError( path_string, ErrorCode::FileOpenError, SOURCE_REF, "File not found"); } } The Error I get is: terminate called after throwing an instance of 'sol::error' what(): lua: error: Problem opening file: (possible cause: "File not found") (at src/extractor/raster_source.cpp:112) I found a lot of questions regarding this issue but I didn't understand any of the answers. I hope someone here can help me with this. Thanks in advance.
If your file is at e:/docker/rastersource.asc on your host, it should be at /data/rastersource.asc inside your container. If your container has bash (for example) then it can be helpful to do something like docker run -it -v e:/docker:/data osrm/osrm-backend osrm-extract bash to run your container interactively, in order to manually have a look in the container filesystem and maybe run whatever other commands interactively.
73,290,845
73,300,634
CLion doesn't sort include statements on commit
I'm using clang-format to define rules for sorting my include statements. This works perfectly when using the "Code > Reformat Code" button or pressing CTRL + ALT + L within a file. However, even when setting the "Reformat code" checkbox in the CLion commit dialog, the include statements don't get sorted when commiting. For some reason other formatting tasks (such as fixing indentation) take place when commiting. It's just the include sorting that's missing. Does anybody know why that is the case? Many thanks! From the .clang-format file: IncludeCategories: - Regex: '^<.*\.h>' Priority: 1 - Regex: '^<[^.]*>' Priority: 2 - Regex: '<.*>' Priority: 3 - Regex: '.*' Priority: 3 IncludeBlocks: Regroup SortIncludes: true
JetBrains Support confirmed to be that this is a bug within CLion that they managed to reproduce on their system. Hoping for it to be fixed in a future version :)
73,291,186
73,291,445
How to define a unique object in a for loop in C++
I have java/python experience and recently started working on a C++ project. I ran into this very generic problem and wasn't able to find any clear answer/explanation in StackOverflow. The concepts behind is probably very basic, but still most of the things I tried seems to fail this far, so I thought it is worth to post it here and learn the "proper C++ way". I'm trying to create a vector of objects in a for loop. The code I have is something like below which works: int NUMBER_OF_OBJECTS = 6; std::vector<SomeObject> objects = std::vector<SomeObject>(NUMBER_OF_OBJECTS); for (int i = 0; i < NUMBER_OF_OBJECTS; i++) { std::string name = "Object" + std::to_string(i); test::SetObject(&objects[i], name.data()); } however if I try something like: std::vector<SomeObject> objects; for (int i = 0; i < 6; i++) { std::unique_ptr<SomeObject> object = std::make_unique<SomeObject>(); objects.push_back(*object.get()); std::string name = "Object" + std::to_string(i); test::SetObject(&objects[i]); } it doesn't work (ie below prints the same address): for (SomeObject o : objects) { std::cout << "object address: " << &o << "\n"; } I thought that's because the docs of unique_ptr says "The object is destroyed and its memory deallocated when ... unique_ptr managing the object is destroyed". So I tried to preserve the unique_ptr by creating a vector of it, something like: std::vector<std::unique_ptr<SomeObject>> objects; for (int i = 0; i < 6; i++) { std::unique_ptr<SomeObject> object = std::make_unique<SomeObject>(); objects.push_back(object); std::string name = "Object" + std::to_string(i); test::SetObject(&(*objects[i].get())); } but instead of preserving the unique_ptr, this instead still destroys the object and warns me call to implicitly-deleted copy constructor of 'std::unique_ptr<SomeObject>' I guess putting the unique_ptr to a vector is not enough to make C++ not destroy that unique_ptr, maybe I need to do something like std::move? I feel like something as basic as initialising a list of objects is probably done very frequently and should have a simpler way to it. I would greatly appreciate if anyone could elaborate how memory management works in C++ for practical purposes (eg. I know I could use new, but read that in most cases I should use make_unique instead to avoid leaking memory)
std::unique_ptr<SomeObject> object = std::make_unique<SomeObject>(); objects.push_back(*object.get()); can be simplified to SomeObject object{}; objects.push_back(object); or even objects.emplace_back(); Your issue in 2nd/3rd snippet is that vector is resized, so inernal pointer and iterator are invalidated: test::SetObject(&objects[i]); // dangling pointer after objects.push_back(*object.get()); std::vector::reserve might solve your issue: std::vector<SomeObject> objects; object.reserve(6); for (int i = 0; i < 6; i++) { SomeObject object{}; objects.push_back(object); std::string name = "Object" + std::to_string(i); test::SetObject(&objects[i]); } or use vector of (smart) pointer: std::vector<std::unique_ptr<SomeObject>> objects; // object.reserve(6); // No longer needed for (int i = 0; i < 6; i++) { std::unique_ptr<SomeObject> object = std::make_unique<SomeObject>(); objects.push_back(std::move(object)); // or simply // objects.push_back(std::make_unique<SomeObject>()); std::string name = "Object" + std::to_string(i); test::SetObject(objects[i].get()); }
73,292,017
73,295,937
CMake FindFLEX produces NOTFOUND on windows
I installed flex and bison with chocolatey choco install winflexbison3 and created this CMakeLists.txt find_package(BISON) find_package(FLEX) message("FLEX_FOUND: ${FLEX_FOUND}") message("FLEX_EXECUTABLE: ${FLEX_EXECUTABLE}") message("FLEX_INCLUDE_DIRS: ${FLEX_INCLUDE_DIRS}") message("FLEX_LIBRARIES: ${FLEX_LIBRARIES}") BISON_TARGET(MyParser parser.y ${CMAKE_CURRENT_BINARY_DIR}/parser.cpp) FLEX_TARGET(MyScanner lexer.l ${CMAKE_CURRENT_BINARY_DIR}/lexer.cpp) ADD_FLEX_BISON_DEPENDENCY(MyScanner MyParser) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_executable(Foo ${BISON_MyParser_OUTPUTS} ${FLEX_MyScanner_OUTPUTS} ) target_link_libraries(Foo ${FLEX_LIBRARIES}) I wrote a dummy parser (copied from https://aquamentus.com/flex_bison.html) and tried to build the project -- Found BISON: C:/ProgramData/chocolatey/bin/win_bison.exe (found version "3.7.4") -- Found FLEX: C:/ProgramData/chocolatey/bin/win_flex.exe (found version "2.6.4") FLEX_FOUND: TRUE FLEX_EXECUTABLE: C:/ProgramData/chocolatey/bin/win_flex.exe FLEX_INCLUDE_DIRS: FLEX_INCLUDE_DIR-NOTFOUND FLEX_LIBRARIES: FL_LIBRARY-NOTFOUND CMake Warning (dev) in CMakeLists.txt: No cmake_minimum_required command is present. A line of code such as cmake_minimum_required(VERSION 3.23) should be added at the top of the file. The version specified may be lower if you wish to support older CMake versions for this project. For more information run "cmake --help-policy CMP0000". This warning is for project developers. Use -Wno-dev to suppress it. -- Configuring done CMake Error: The following variables are used in this project, but they are set to NOTFOUND. Please set them or make sure they are set and tested correctly in the CMake files: FL_LIBRARY (ADVANCED) linked by target "Foo" in directory C:/Users/Aleksander/source/repos/C/insilico/blender/test -- Generating done CMake Generate step failed. Build files cannot be regenerated correctly. For some reason CMake can't find the library and include dir. What should I do? Where does FLEX expect the libraries to be? This is what I did so far: I see FlexLexer.h to be right there C:\ProgramData\chocolatey\lib\winflexbison3\tools> ls FlexLexer.h changelog.md custom_build_rules win_bison.exe UNISTD_ERROR.readme chocolateyInstall.ps1 data win_flex.exe I see that FindFLEX uses this source code to look for this file but somehow fails https://github.com/Kitware/CMake/blob/241fc839d56ccd666fe41269e291b8d8190cf97b/Modules/FindFLEX.cmake#L117 find_library(FL_LIBRARY NAMES fl DOC "Path to the fl library") find_path(FLEX_INCLUDE_DIR FlexLexer.h DOC "Path to the flex headers") mark_as_advanced(FL_LIBRARY FLEX_INCLUDE_DIR) set(FLEX_INCLUDE_DIRS ${FLEX_INCLUDE_DIR}) set(FLEX_LIBRARIES ${FL_LIBRARY}) I found this documentation for find_path http://devdoc.net/linux/cmake-3.9.6/command/find_path.html and there is a list of paths that are searched. I queried them with message("CMAKE_INCLUDE_PATH: ${CMAKE_INCLUDE_PATH}") message("CMAKE_FRAMEWORK_PATH: ${CMAKE_FRAMEWORK_PATH}") message("CMAKE_SYSTEM_INCLUDE_PATH: ${CMAKE_SYSTEM_INCLUDE_PATH}") message("CMAKE_SYSTEM_FRAMEWORK_PATH: ${CMAKE_SYSTEM_FRAMEWORK_PATH}") message("CMAKE_LIBRARY_ARCHITECTURE: ${CMAKE_LIBRARY_ARCHITECTURE}") message("CMAKE_FIND_ROOT_PATH: ${CMAKE_FIND_ROOT_PATH}") message("CMAKE_SYSROOT: ${CMAKE_SYSROOT}") and got CMAKE_INCLUDE_PATH: CMAKE_FRAMEWORK_PATH: CMAKE_SYSTEM_INCLUDE_PATH: CMAKE_SYSTEM_FRAMEWORK_PATH: CMAKE_LIBRARY_ARCHITECTURE: CMAKE_FIND_ROOT_PATH: CMAKE_SYSROOT: So it seems that find_path does absolutely nothing. Should I specify the paths myself? But is such case what is CMake even for?
It's astounding how many irritating problems are caused by a trivial library file which probably shouldn't exist anyway, and which is hardly ever needed. The library in question was originally called libl (l for lex), and Posix requires that when you link executables which include a lex-generated scanner, you add -ll to the linker invocation. Flex, which to all intents and purposes is the current successor to the Lex tool, decided to change the name of the library to libfl, and that's generally what you'll find in a Flex installation. So the usual instructions you'll find these days (i.e., for the last several decades) say that you should use the command-line option -lfl. Often, but not always, distributions add a symbolic link (or equivalent) for libl so that the Posix-specified -ll still works. Occasionally, the Flex distribution is modified so that the library is called libl, in which case -lfl won't work. And sometimes, the library isn't part of the distribution at all and needs to be acquired from a different package. Posix wanted to cater for a Lex implementation which puts some functions into a library instead of generating the same code each time. But few (if any) lex implementations ever took advantage of that provision; in particular, Flex-generated scanners have no reliance on libfl for any internal function. There are only two functions defined in that library: int main(void) { while (yylex()) {} } int yywrap(void) { return 1; } The first one is a default implementation of main which just calls yylex until it returns 0 (indicating EOF). That can be handy for quick-and-dirty scanner rule tests, but any real project will certainly have a main() definition. The second provides a default yywrap implementation. However, Flex provides an even simpler way of indicating that the yywrap functionality isn't required: %option noyywrap If you don't require yywrap, you should just add the above to your .l file (in the prologue). If you do require yywrap, then you need to define it. In either case, you don't need the library. So my recommendation is that rather wasting your time trying to figure out the deficiencies of the flex packaging you're using, just add the above %option to your Flex input file and eliminate the library from your build rules.
73,292,407
73,292,900
How can I couple the lifetimes of two variables?
The following code compiles and runs fine, but does not work as intended (compare the comments in the code). I believe the reason is that the lifetime of is ends with getFileIter, so the stream buffer iterator has nothing left to iterate over. (By contrast, I think I remember that in C#, is would live as long as the stream buffer iterator points to it, but that does not seem to be the case in C++.) One fix to avoid this is using ... *is = new std::ifstream(p), but this means I have to take care of the pointer myself when I'm done. Is there any mechanism to link the lifetimes of is and its stream buffer iterator? // g++ test.cpp -o test && ./test #include <iostream> #include <fstream> std::istreambuf_iterator<char> getFileIter(std::string p) { std::ifstream is(p); //std::ifstream *is = new std::ifstream(p); std::cout << "Read " << p << "? " << is.good() << std::endl; return std::istreambuf_iterator<char>(is.rdbuf()); } int main() { std::string p1("/etc/passwd"); std::string p2("/etc/group"); // Prints 1 as if the two files were identical std::cout << std::equal( getFileIter(p1), std::istreambuf_iterator<char>(), getFileIter(p2) ) << std::endl; // Prints nothing except ///// auto x = getFileIter(p1); int i = 0; do { std::cout << *(x++) << "/"; i++; } while (i < 5); std::cout << std::endl; return 0; }
As one comment suggests, combine both things: stream and its iterator in a struct - to ensure the iterator will not outlive the stream: struct FileIter { FileIter(const std::string& p) : is(p), iter(is.rdbuf()) {} std::ifstream is; std::istreambuf_iterator<char> iter; }; std::cout << std::equal( FileIter(p1).iter, std::istreambuf_iterator<char>(), FileIter(p2).iter ) << std::endl; FileIter x(p1); int i = 0; do { std::cout << *(x.iter++) << "/"; i++; } while (i < 5); std::cout << std::endl; If you like -- you might make this FileIter looks like iterator - see this post Two important things: In this code: std::cout << std::equal( FileIter(p1).iter, std::istreambuf_iterator<char>(), FileIter(p2).iter ) << std::endl; FileIter might be temporary (nameless) because its lifetime is guaranteed to be as long as to the end of expression (the semicolon). Here, you cannot replace FileIter x(p1); with auto x = FileIter(p1).iter; because stream in FileIter will end its lifetime with the end of expression (semicolon here). FileIter x(p1); int i = 0; do { std::cout << *(x.iter++) << "/"; i++; } while (i < 5); std::cout << std::endl;
73,292,603
73,298,217
Printing a compile-time string_view
Say I have a metafunction that returns a std::string_view template<typename T> struct type_to_string; template <typename T> constexpr std::string_view type_to_string_v = type_to_string<T>::value; and a string_view resulting from this: constexpr auto sv = type_to_string_v<very_complex_expression>; Is there any way to print the value of this string at compile-time? (ie. as part of some compiler error message or static assert)
Here's a modification of OP's solution that produces a somewhat more readable message with gcc. Unfortunately, with clang the message is rather less readable, and MSVC doesn't work at all (due to a compiler bug I suppose). #include <cstdlib> #include <algorithm> #include <string_view> #include <utility> template <size_t N> struct FS { // fixed size string char chars[N + 1] = {}; constexpr FS(const char (&str)[N + 1]) { std::copy_n(str, N + 1, chars); } }; template <size_t N> FS(const char (&str)[N])->FS<N - 1>; template<typename T> struct type_to_string; template<> struct type_to_string<int> { constexpr static auto value = "integer"; }; template <auto> constexpr bool string_value = false; template<FS fs> // size will be deduced void compile_time_display() { static_assert(string_value<fs>); } int main() { constexpr std::string_view sv = type_to_string<int>::value; constexpr size_t n = sv.size(); constexpr auto indices = std::make_index_sequence<n>(); [&] <std::size_t... I> (std::index_sequence<I...>) { static constexpr char text[] { (char)sv.at(I)..., 0 }; compile_time_display<text>(); // the char array will convert to FS }(indices); } The message shown by gcc reads: main.cc: In instantiation of ‘void compile_time_display() [with FS<...auto...> fs = FS<7>{"integer"}]’ ... main.cc:26:23: note: ‘string_value<FS<7>{"integer"}>’ evaluates to false
73,292,840
73,292,889
What is wrong in this program //trying to reverse an array?
I am trying to create a program to reverse an array by creating a temporary array defined within a fucntion and then copying the elements of the from the end of array to the start of the temporary array. #include<iostream> using namespace std; void reverse(int arr[]) { int revarray[10]; for(int i=0;i<10;i++) for(int j=9;j>=0;j--) { revarray[j]=arr[i]; } for(int k=0;k<10;k++) { cout<<revarray1[k]<<" "; } } int main() { int arr[10]; cout<<"Enter the elements of array"<<endl; for(int i=0;i<10;i++) { cin>>arr[i]; } reverse(arr); } This is the output that i am getting
In these nested for loops for(int i=0;i<10;i++) for(int j=9;j>=0;j--) { revarray[j]=arr[i]; } you are setting all elements of the array revarray with values of the array arr within the inner for loop in each iteration of the outer for loop. As a result after the loops all elements of the array revarray contain the value arr[9]. In any case the function is wrong because it uses the magic number 10. So it may not be called for arrays with other numbers of elements. If you want to reverse an array then the function can look for example the following way as shown in the demonstration program below. #include <iostream> #include <utility> void reverse( int arr[], size_t n ) { for ( size_t i = 0; i < n / 2; i++ ) { std::swap( arr[i], arr[n - i - 1] ); } } int main() { const size_t N = 10; int arr[N]; std::cout << "Enter the elements of array" << std::endl; for ( size_t i = 0; i < N; i++ ) { std::cin >> arr[i]; } reverse( arr, N ); for ( const auto &item : arr ) { std::cout << item << ' '; } std::cout << std::endl; } Pay attention to that there is standard algorithm std::reverse declared in header <algorithm> that can be used with arrays. In this case to reverse an array you could write #include <iterator> #include <algorithm> //... std::reverse( std::begin( arr ), std::end( arr ) );
73,292,998
73,294,171
Destructor, when object's dynamic variable is locked by mutex will not free it?
I'm trying to solve some complicated (for me at least) asynchronous scenario at once, but I think it will be better to understand more simple case. Consider an object, that has allocated memory, carrying by variable: #include <thread> #include <mutex> using namespace std; mutex mu; class Object { public: char *var; Object() { var = new char[1]; var[0] = 1; } ~Object() { mu.lock(); delete[]var; // destructor should free all dynamic memory on it's own, as I remember mu.unlock(); } }*object = nullptr; int main() { object = new Object(); return 0; } What if while, it's var variable in detached, i.e. asynchronous thread, will be used, in another thread this object will be deleted? void do_something() { for(;;) { mu.lock(); if(object) if(object->var[0] < 255) object->var[0]++; else object->var[0] = 0; mu.unlock(); } } int main() { object = new Object(); thread th(do_something); th.detach(); Sleep(1000); delete object; object = nullptr; return 0; } Is is it possible that var will not be deleted in destructor? Do I use mutex with detached threads correctly in code above? 2.1 Do I need cover by mutex::lock and mutex::unlock also delete object line? I also once again separately point that I need new thread to be asynchronous. I do not need the main thread to be hanged, while new is running. I need two threads at once. P.S. From a list of commentaries and answers one of most important thing I finally understood - mutex. The biggest mistake I thought is that already locked mutex skips the code between lock and unlock. Forget about shared variables, mutex itself has noting to do with it. Mutex is just a mechanism for safely pause threads: mutex mu; void a() { mu.lock(); Sleep(1000); mu.unlock(); } int main() { thread th(a); th.detach(); mu.lock(); // hangs here, until mu.unlock from a() will be called mu.unlock(); return; } The concept is extremely simple - mutex object (imagine) has flag isLocked, when (any) thread calls lock method and isLocked is false, it just sets isLocked to true. But if isLocked is true already, mutex somehow on low-level hangs thread that called lock until isLocked will not become false. You can find part of source code of lock method scrolling down this page. Instead of mutex, probably just a bool variable could be used, but it will cause undefined behaviour. Why is it referred to shared stuff? Because using same variable (memory) simultaneously from multiple threads makes undefined behaviour, so one thread, reaching some variable that currently can be used by another - should wait, until another will finish working with it, that's why mutex is used here. Why accessing mutex itself from different threads does not make undefined behaviour? I don't know, going to google it.
Is is it possible that var will not be deleted in destructor? With ~Object() { mu.lock(); delete[]var; // destructor should free all dynamic memory on it's own, as I remember mu.unlock(); } You might have to wait that lock finish, but var would be deleted. Except that your program exhibits undefined behaviour with non protected concurrent access to object. (delete object isn't protected, and you read it in your another thread), so everything can happen. Do I use mutex with detached threads correctly in code above? Detached or not is irrelevant. And your usage of mutex is wrong/incomplete. which variable should your mutex be protecting? It seems to be a mix between object and var. If it is var, you might reduce scope in do_something (lock only in if-block) And it misses currently some protection to object. 2.1 Do I need cover by mutex::lock and mutex::unlock also delete object line? Yes object need protection. But you cannot use that same mutex for that. std::mutex doesn't allow to lock twice in same thread (a protected delete[]var; inside a protected delete object) (std::recursive_mutex allows that). So we come back to the question which variable does the mutex protect? if only object (which is enough in your sample), it would be something like: #include <thread> #include <mutex> using namespace std; mutex mu; class Object { public: char *var; Object() { var = new char[1]; var[0] = 1; } ~Object() { delete[]var; // destructor should free all dynamic memory on it's own, as I remember } }*object = nullptr; void do_something() { for(;;) { mu.lock(); if(object) if(object->var[0] < 255) object->var[0]++; else object->var[0] = 0; mu.unlock(); } } int main() { object = new Object(); thread th(do_something); th.detach(); Sleep(1000); mu.lock(); // or const std::lock_guard<std::mutex> lock(mu); and get rid of unlock delete object; object = nullptr; mu.unlock(); return 0; } Alternatively, as you don't have to share data between thread, you might do: int main() { Object object; thread th(do_something); Sleep(1000); th.join(); return 0; } and get rid of all mutex
73,293,131
73,293,452
Start QProcess on button press
I'm building an application that launches an exe file on button press with QProcess. I have multiple buttons that are created in this way: Program reads from local database the information needed to create buttons (name, exe path) Then for each entry in the database it creates a button with the associated name in a previously created QFrame. How can I associate the respective executable with the button? Code QSqlQueryModel query; query.setQuery("SELECT * FROM games"); if (!query.record(0).isEmpty()) { for (int i = 0; i < query.rowCount(); i++) { QPushButton* button = new QPushButton(query.record(i).value("name").toString(), ui->frame); button->setGeometry(120 * (ui->frame->findChildren<QPushButton*>().size() - 1), 0, 110, 150); button->show(); } } Notes: The number of buttons in the frame is random System Info: I'm on Windows 11, using Qt 6.3.1 MSVC 64-bit
I would use a lmbda like this: QSqlQueryModel query; query.setQuery("SELECT * FROM games"); if (!query.record(0).isEmpty()) { for (int i = 0; i < query.rowCount(); i++) { QPushButton* button = new QPushButton(query.record(i).value("name").toString(), ui->frame); button->setGeometry(120 * (ui->frame->findChildren<QPushButton*>().size() - 1), 0, 110, 150); connect(button, &QPushButton::clicked, [=] { // Insert button specific code inside this lambda }); button->show(); } } From the docs: Qt 6 Signals and Slots
73,293,281
73,293,332
Constructor of struct calling the member function of another class declared as a pointer
I have the following code: class Cohomology; struct EMField { std::unique_ptr<Cohomology> coh; std::array<DIM> data; EMField() {coh -> initializeField(*this);}; } class Cohomology { private: // private members public: Cohomology(PList params) { // Constructor of the class } void initializeField(EMField& field) { field.coh.reset(this); // other methods to initialize field.data using the private members } } In this answer it is explained that calling a method of an incomplete type is not possible, nor dereferencing the pointer. In fact, when I try to compile it I get: warning: invalid use of incomplete type ‘class Cohomology‘ note: forward declaration of ‘class Cohomology‘ My question is: How can I delegate the construction of EMField to the Cohomology class if I cannot use a member of std::unique_ptr<Cohomology> coh ?
Just move the definition of EMField::EMField() until after both classes have been defined. class Cohomology; struct EMField { std::unique_ptr<Cohomology> coh; std::array<DIM> data; EMField(); }; class Cohomology { private: // private members public: Cohomology(PList params) { // Constructor of the class } void initializeField(EMField& field) { field.coh.reset(this); // other methods to initialize field.data using the private members } }; inline EMField::EMField() { coh -> initializeField(*this); }
73,293,420
73,293,500
Const correctness in generic functions using iterators
I want to write a generic functions that takes in a sequence, while guaranteeing to not alter said sequence. template<typename ConstInputIter, typename OutputIter> OutputIter f(ConstInputIter begin, ConstInputIter end, OutputIter out) { InputIter iter = begin; do { *out++ = some_operation(*iter); }while(iter!=end); return out; } Yet the above example still would take any type as ConstInputIterator, not just const ones. So far, the notion towards being const in it is nominal. How do I declare the sequence given will not be altered by this function?
Even in C++20, there is no generic way to coerce an iterator over a non-const T into an iterator over a T const. Particular iterators may have a mechanism to do that, and you can use std::cbegin/cend for ranges to get const iterators. But given only an iterator, you are at the mercy of what the user provides. Applying a C++20 constraint (requiring iter_value_t to be const) is the wrong thing, as your function should be able to operate on a non-const range.
73,293,583
73,309,737
Using iterator to retrieve const values pointed to in containers
Const casting container value-types seems not possible. A comment in the other question suggests iterators as a solution, yet does not go into detail. Since I seemingly cannot simply convert a container from a non-const to a const version as a function parameter, I arrive at Iterators to maybe be able to do the job. I actually have a vector<shared_ptr<Thing> > to be treated as const vector<shared_ptr<Thing const> >. With it I intend to use the shared_ptr<Thing const> as further references in other structures, without allowing those structures to alter the Things. Those structures may create their own objects, stored by their own shared_ptr, if they want slightly different content within their containers, while still actively sharing most Things with other objects. So I would need either shared_ptr<const Thing>&, or const shared_ptr<const Thing>& from an Iterator through the sequence. Either would suffice, but just because one can be indifferent about passing references in this example, because of shared_ptr's copy semantics are about just that. Yet even just using default const_iterator, retrieved by cbegin(),c.end() and such, will give me a const shared_ptr<Thing>& instead. Edit: To copy the vector element for element would be one way technically, as in the other question, yet undesired for interface reasons. I am going for reinterpretation here, not copy. Any suggestions on where a workaround might lie?
Based on your situation, it sounds like defining a custom iterator with the semantics you want is the safe and simple way to go. It's technically correct, hard to accidentally misuse, and fairly fast, just requiring a shared_ptr copy on iterator dereference. I always recommend boost::iterator_facade or boost::iterator_adaptor for creating an iterator type. Since it will contain the original vector iterator as a "base" implementation, iterator_adaptor is helpful. class const_Thing_ptr_iterator : public boost::iterator_adaptor< const_Thing_ptr_iterator, // CRTP derived type std::vector<std::shared_ptr<Thing>>::const_iterator, // base iterator type std::shared_ptr<const Thing>, // value_type std::random_access_iterator_tag, // traversal type std::shared_ptr<const Thing> // reference > { public: const_Thing_ptr_iterator() = default; explicit const_Thing_ptr_iterator(base_type iter) : iterator_adaptor(iter) {} }; The reference iterator type would be std::shared_ptr<const Thing>& by default, but in this case it can't be a reference since there is no object of that type. Normally the class would define some of the behavior functions like dereference or increment, but none are needed here: the only change from the base vector iterator is to the return type of operator*, and the default reference dereference() const { return *base_reference(); } works fine by implicit conversion from const std::shared_ptr<Thing>& to std::shared_ptr<const Thing>. The class could also be a template taking Thing as its type parameter, to create multiple iterator types. Then to provide a container-like view object, we can use C++20's std::ranges::subrange to provide begin() and end() and a few other things helping the out the range templates: #include <ranges> class const_Thing_ptrs_view : public std::ranges::subrange<const_Thing_ptr_iterator> { public: explicit const_Thing_ptrs_view(const std::vector<std::shared_ptr<Thing>> &vec) : subrange(const_Thing_ptr_iterator(vec.begin()), const_Thing_ptr_iterator(vec.end())) {} }; Or if that's not available, a simple class with begin() and end(): class const_Thing_ptrs_view { public: explicit const_Thing_ptrs_view(const std::vector<std::shared_ptr<Thing>> &vec) : m_begin(vec.begin()), m_end(vec.end()) {} const_Thing_ptr_iterator begin() const { return m_begin; } const_Thing_ptr_iterator end() const { return m_end; } private: const_Thing_ptr_iterator m_begin; const_Thing_ptr_iterator m_end; }; Demo on godbolt. (Clang doesn't like the ranges code due to this libstdc++ incompatibility; I'm not sure how to get godbolt to switch it to clang's libc++.)
73,293,661
73,304,759
What WinAPI feature could change the width of window border on Win7
I'm just noticed that a new version of my app has broader borders on Windows 7 (there is no difference in Win10): The background window is my new version and the foreground window is an older version. I'm trying to find difference in git, but with no luck yet. I have tried to set different border styles in resource editor of Visual Studio, e.g. None, Thin, Resizing etc. - it does change nothing. Also I have tried to set different styles via SetWindowLong (I found examples somewhere in SO): LONG lStyle = GetWindowLong(mainWindow.GetWindowHandle(), GWL_STYLE); lStyle &= ~(WS_THICKFRAME | WS_MINIMIZEBOX | WS_MAXIMIZEBOX); SetWindowLong(mainWindow.GetWindowHandle(), GWL_STYLE, lStyle); LONG lExStyle = GetWindowLong(mainWindow.GetWindowHandle(), GWL_EXSTYLE); lExStyle &= ~(WS_EX_DLGMODALFRAME | WS_EX_CLIENTEDGE | WS_EX_STATICEDGE); SetWindowLong(mainWindow.GetWindowHandle(), GWL_EXSTYLE, lExStyle); While changing the style I can change only the presence of titlebar, buttons, etc., but borders' size on Win7 always remains the same. UPDATE: Answer to commenters. @Junjie Zhu. I didn't change PaddedBorderWidth. I suppose it controls all applications, but I can run both versions of my app simultaneously and older version will have thin borders, and newer version will have thick borders. @Paul Sanders and @Anders. I have checked manifest file - the only difference is that I had added DPI-awareness setting for Win10: <dpiAwareness xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">PerMonitorV2</dpiAwareness> I have tried to remove it - nothing had changed. All other strings in manifest file are the same. Specifically, it has all fields for supporting Os'es from WinVista to Win10/11: <compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1"> <application> <supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}"/> <supportedOS Id="{1f676c76-80e1-4239-95bb-83d0f6d0da78}"/> <supportedOS Id="{e2011457-1546-43c5-a5fe-008deee3d3f0}"/> <supportedOS Id="{35138b9a-5d96-4fbd-8e2d-a2440225f93a}"/> <supportedOS Id="{4a2f28e3-53b9-4441-ba9c-d69d4a4a6e38}"/> </application> </compatibility> I cann't imagine which of other fields can control borders' size.
It seems I've found the reason - I have switched Platform toolset from v120_xp to the latest v143. May be somebody knows how to retain thin borders with new toolset? UPDATE: Wow! Thanks to Hans Passant! When using newer version of toolset just set Minimum required version to 5.02. Now it works.
73,294,794
73,296,100
Replace text \n with actual new line. (C++)
I'm using C++ and I have a problem. Instead of creating a new line it prints \n. My Code: std::string text; std::cout << text; It prints:Hello\nWorld It was supposed to read \n as a new line and print something like this: "Hello World" So i've tried to use replace(text.begin(), text.end(), '\n', 'a') for testing purposes and nothing happened. It contiuned to print Hello\nWorld
std::replace() won't work in this situation. When called on a std::string, it can replace only single characters, but in your case your string actually contains 2 distinct characters '\' and 'n'. So you need to use std::string::find() and std::string::replace() instead, eg: string::size_type index = 0; while ((index = str.find("\\n", index)) != string::npos) { str.replace(index, 2, "\n"); ++index; }
73,294,887
73,296,263
Why does std::variant behave differently on GCC 8.5 and GCC 12.1 in respect to a `const char *` literal?
#include <iostream> #include <string> #include <variant> int main() { std::variant<std::string, bool> v{ "hasta la vista" }; std::cout << std::boolalpha << std::holds_alternative<std::string>(v) << ' ' << std::holds_alternative<bool>(v) << std::endl; } GCC 12.1.1 $ g++ std_alternative.cpp $ ./a.out true false GCC 8.5.0 $ g++ -std=c++17 std_alternative.cpp $ ./a.out false true Why is the output different? Which is correct according to c++17? What should I do so that my code works on both versions of GCC the same way?
struct explicit_bool { bool b = false; template<class T, std::enable_if_t<std::is_same_v<T, bool>, bool> = true > explicit_bool( T v ):b(v){} explicit_bool(explicit_bool const&) noexcept=default; explicit_bool& operator=(explicit_bool const&)& noexcept=default; explicit_bool()noexcept=default; ~explicit_bool()noexcept=default; bool operator!() const { return !b; } explicit operator bool() const { return b; } }; store one of these (instead of a bool). It only accepts actual bools and other explicit_bools as arguments. You may have to add some explicit casts to-from bool in your code after doing this. It may be of interest to you that (bool) as a cast always does the exact same thing as static_cast<bool> does, unlike many other C-style casts compared to C++ style casts; this can make it less painful. Another choice is !!, which converts most types to bool implicitly.
73,295,103
73,295,310
Passing variadic template parameter to another function with a variadic template parameter
I'm currently writing a logger for my engine and I've been stuck with a problem I could not solve. std::format takes in a constant string and a list of arguments after. My Log functions is as follows: template <typename... Args> void Log(const char* message, Args&&... args) Now in somewhere in the function scope, I try to format the string by: std::string formattedMsg = std::format(message, args); And I try to mess with it: Scope<Colour::Logger> myLogger = CreateScope<Colour::Logger>("MyLogger"); myLogger->Log("Hey! I have a variable named \"a\" and it is equal to {0}", a); myLogger->Info("Hey! I have a variable named \"a\" and it is equal to {0}", a); myLogger->Log("Hey! I have a variable named \"a\" and it is equal to {0}", a); myLogger->Warn("Hey! I have a variable named \"a\" and it is equal to {0}", a); myLogger->Error("Hey! I have a variable named \"a\" and it is equal to {0}", a); myLogger->Fatal("Hey! I have a variable named \"a\" and it is equal to {0}", a); myLogger->Info("Hey! I have a variable named \"a\" and it is equal to {0}", a); Scope is unique_ptr, CreateScope is make_unique. Info, Fatal, Trace etc. functions just set the level to correct one and call Log(). But that gives me the error: std::_Basic_format_string::_Basic_format_string': call to immediate function is not a constant expression I tried doing stuff like taking in a _Fmt_String, std::string, const char*, I tried expanding the arguments, forwarding them but none of them work. How can I format this message parameter using the args parameter using std::format?
This might get you started : #include <iostream> #include <format> template <typename... args_t> void Log(const std::string_view& fmt, args_t&&... args) { std::string formatted_message = std::vformat(fmt, std::make_format_args(std::forward<args_t>(args)...)); std::cout << formatted_message << "\n"; } int main() { Log("Hello {0}{1}", "World", "!"); return 0; }
73,296,287
73,304,211
Garbage value in rapid json AddMember
{ std::string result; RapidJSON::Value json; json.SetObject(); for(int i = 0; i < 5; ++i) { RapidJSON::Value data; data.SetObject(); for(auto it = HashMap.begin(); it != HashMap.end(); it++) { RapidJSON::Value arrObj; arrObj.SetObject(); for(auto it2 = it->second.begin(); it2 != it->second.end(); it2++) { arrObj.AddMember(RapidJSON::StringRef(it2->first.c_str()), RapidJSON::StringRef(it2->second.c_str()), d.GetAllocator()); } data.AddMember(RapidJSON::StringRef(it->first.c_str()), RapidJSON::Value(arrObj, d.GetAllocator()).Move(), d.GetAllocator()); } json.AddMember(RapidJSON::StringRef(str.c_str()), RapidJSON::Value(data, d.GetAllocator()).Move(), d.GetAllocator()); } cleanup: retJson.AddToJson(RapidJSON::StringRef("STATUS"), json); result = retJson.ToString(); } I am using this method to convert a map to a json, but after each iteration of the outer for loop the value in the json value changes, the value assigned during the previous iteration becomes garbage values Can't find any solution, I have tried using creating a new Value and using the Move method, but that also didn't help
don't use stringRef, instead create a copy of the strings in both arrObj, data member Sample code RapidJSON::Value key(it2->first.c_str(), d.GetAllocator()); arrObj.AddMember(key, it2->second, d.GetAllocator());
73,296,745
73,296,855
C++ project crashes after glewinit()
(Im using Clion and Cmake on Macosx Intel chip) I wan't to make a Window Application with GLEW. But i get this error: Process finished with exit code 139 (interrupted by signal 11: SIGSEGV) I heard that you should define "GLEW_STATIC" in the preprocessing. But I have no idea how Clion works My main.cpp: #include "GL/glew.h" #include <GLFW/glfw3.h> int main() { GLFWwindow* window; if (!glfwInit()) return -1; glewInit(); window = glfwCreateWindow(640, 480, "Hello World", NULL, NULL); if (!window) { glfwTerminate(); return -1; } glfwMakeContextCurrent(window); while (!glfwWindowShouldClose(window)) { glClear(GL_COLOR_BUFFER_BIT); glfwSwapBuffers(window); glfwPollEvents(); } glfwTerminate(); return 0; } and my cmake: cmake_minimum_required(VERSION 3.22) project(renderer) set(CMAKE_CXX_STANDARD 14) include_directories(/usr/local/Cellar/glfw/3.3.8/include) include_directories(/usr/local/Cellar/glew/2.2.0_1/include) add_definitions(-DGLEW_STATIC) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -framework CoreFoundation -framework OpenGL -framework GLUT ") add_executable(renderer main.cpp) target_link_libraries(renderer /usr/local/Cellar/glfw/3.3.8/lib/libglfw.3.3.dylib) target_link_libraries(renderer /usr/local/Cellar/glew/2.2.0_1/lib/libGLEW.2.2.dylib) How do i fix this problem?
glewInit() requires a current OpenGL context to operate correctly. As written in your code glewInit() will fail and leave its glClear() function-pointer set to nullptr. Call glewInit() after glfwMakeContextCurrent() 'returns' GLFW_NO_ERROR and verify that it returns GLEW_OK.
73,297,830
73,297,875
Returning a reference to std::vector element results in a crash
The example below does not crash, but prints nothing with MSVC Compiler Version 19.32.31332 and prints "def" with GCC: #include <string> #include <vector> #include <set> #include <ranges> #include <iostream> template <class R, class Value> concept range_over = std::ranges::range<R> && std::same_as<std::ranges::range_value_t<R>, Value>; const std::string& find1(const std::vector<std::string>& v) { return v[1]; } template <range_over<std::string> Range> std::reference_wrapper<std::string> find2(Range range) { return *(range.begin() + 1); } int main() { std::vector<std::string> v = { "abc", "def", "ghi" }; //find1 always prints "def" //std::cout << find1(v); std::cout << find2(v).get() << std::endl; return 0; } But in my real-life app a similar code crashes with MSVC Compiler Version 19.32.31332. Is the code correct? Is v valid after func2(v) call?
find2 takes the range by-value. So you are returning a reference into the function parameter object, which is a copy of the vector v in main, which in itself is very likely not the intention of the function. E.g. modifications through the returned reference would not be reflected in v. It is implementation-defined whether function parameters are destroyed when the function returns or after the full-expression containing the function call. Practically speaking this will be determined by the C++ ABI used (which also potentially explains different behavior between MSVC and GCC/Clang). So, depending on how the implementation used defines this, it may or may not have undefined behavior. If the parameter object is destroyed when the function returns, the call to operator<< will read a value through a dangling reference. Otherwise it is a valid program and will print def. Before C++17 the standard said that function parameter objects are always destroyed when the function returns. This was changed with CWG issue 1880. As the issue notes however, actual implementations/ABIs did have the (at the time) non-conforming behavior of destroying them at the end of the full-expression and the implementation-definedness in the resolution was chosen so that these ABIs wouldn't break. So practically speaking the standard just adjusted to actual practice.
73,297,977
73,298,097
Why is VSCode using Cygwin to build and execute my CPP programs?
I downloaded and installed MinGW under C:\MinGw and installed g++ and gcc. If I run g++ --version I get: g++.exe (MinGW.org GCC-6.3.0-1) 6.3.0 Copyright (C) 2016 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE If I run gcc --version, I get: gcc (GCC) 11.3.0 Copyright (C) 2021 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE I'm trying to run a simple helloworld.cpp file from VSCode: #include<iostream> int main() { std::cout << "Hello World" << std::endl; } I've edited the c_cpp_properties.json file as follows: { "configurations": [ { "name": "Win32", "includePath": [ "${workspaceFolder}/**", "C:\\MinGW\\include" ], "defines": [ "_DEBUG", "UNICODE", "_UNICODE" ], "compilerPath": "C:\\MinGW\\bin\\g++.exe", "cStandard": "c17", "cppStandard": "c++17", "intelliSenseMode": "windows-gcc-x64" } ], "version": 4 } But when I go and build/run the file, I get the following: Starting build... C:\cygwin64\bin\cpp.exe -fdiagnostics-color=always -g C:\Users\Pippo\Desktop\Programming\CPP\helloworld.cpp -o C:\Users\Pippo\Desktop\Programming\CPP\helloworld.exe cpp: fatal error: cannot execute 'cc1plus': spawn: No such file or directory compilation terminated. Build finished with error(s). Why is this failing? And why am I seeing Cygwin being called?? EDIT (more stuff I don't get): The behaviour I showed before happens when I click on Run C/C++ File But when I click on Run Code it works (and it calls g++): EDIT (@Yakk - Adam Nevraumont answer): Nope, Cygwin is after g++ in my env vars:
VSCode uses a completely separate tool chain for compiling and for linting and syntax highlighting and similar. c_cpp_properties.json isn't for compiling. It gets the compiler typically from your PATH. See here. Your build task is probably set to the compiler g++, and the first one on the search path (the PATH environment variable) is Cygwin's g++. Alternatively, it can be hard coded in tasks.json.
73,298,338
73,298,496
what is the difference between "return num1<num2" and "return num2-num1" in comparator
I am learning how to write the comparator in C++. At first time, I return num1<num2, as a result I get a set in ascending order. Then I return num1>num2 and I get a set in descending order. Now I try to return num1-num2 which should equal to num1>num2 in my opinion, I get a set in descending order as predicted. But when I try to return num2-num1, I still get a set in descending order. How could it happen? Is there any difference between return num2-num1 and return num1<num2? #include <iostream> #include <set> using namespace std; struct myCmp{ bool operator()(const int& num1, const int& num2){ return num2-num1; } }; int main() { set<int,myCmp> st; st.insert(1); st.insert(2); st.insert(3); for(auto it=st.begin();it!=st.end();it++){ cout<<*it<<endl; } return 0; }
Now I try to return num1-num2 which should equal to num1>num2 in my opinion That is incorrect. Is there any difference between return num2-num1 and return num1<num2? Yes. num2-num1 returns an integer value that is the result of subtracting the value of num1 from the value of num2. Since your comparator returns a bool, a result of 0 will be converted to false, and any other result will be converted to true. num1<num2 returns a boolean value specifying whether or not num1 is actually less-than num2. Any value of num1 that is less-than the value of num2 will return true, all other values will return false. So, as you can see, both approaches return completely different things. std::set has the following requirement: std::set is an associative container that contains a sorted set of unique objects of type Key. Sorting is done using the key comparison function Compare. Search, removal, and insertion operations have logarithmic complexity. Sets are usually implemented as red-black trees. Everywhere the standard library uses the Compare requirements, uniqueness is determined by using the equivalence relation. In imprecise terms, two objects a and b are considered equivalent if neither compares less than the other: !comp(a, b) && !comp(b, a). Using return num1<num2 (or return num1>num2) satisfies that requirement, but return num2-num1 breaks it. For example, let's assume a = 1 and b = 2. Using num1<num2, you get the following: !comp(a, b) && !comp(b, a) = !comp(1, 2) && !comp(2, 1) = !(1 < 2) && !(2 < 1) = !true && !false = false && true = one is less-than the other, so not equal, which is correct! Using num1>num2, you get the following: !comp(a, b) && !comp(b, a) = !comp(1, 2) && !comp(2, 1) = !(1 > 2) && !(2 > 1) = !false && !true = true && false = one is less-than the other, so not equal, which is correct! Using num2-num1, you get the following: !comp(a, b) && !comp(b, a) = !comp(1, 2) && !comp(2, 1) = !(2 - 1) && !(1 - 2) = !(1) && !(-1) = !true && !true = false && false = neither is less-than the other, so equal, which is incorrect!
73,298,399
73,298,639
C++ how can I simplify this if else statement?
I would like to know how I could simplify a statement like the one below. I have similar code everywhere, and would like to clear it up. if(isActive) { if(columnId == 4) g.drawText(active[row].value, 2, 0, width, height, Justification::centredLeft, true); } else { if(columnId == 4) g.drawText(inactive[row].value, 2, 0, width, height, Justification::centredLeft, true); } isActive, as you can imagine, is a bool value.
At first glance, it's most apparent that this code only does anything if columnId == 4. if(columnId == 4) { if(isActive) { g.drawText(active[row].value, 2, 0, width, height, Justification::centredLeft, true); } else { g.drawText(inactive[row].value, 2, 0, width, height, Justification::centredLeft, true); } } At second glance, those two bulky lines are almost the same. if(columnId == 4) { auto & text = isActive ? active : inactive; g.drawText(text[row].value, 2, 0, width, height, Justification::centredLeft, true); } Note, also, the valid comment from @eerorika. ⬇️ I couldn't say it better than they did.
73,298,741
73,298,986
SDL2 Transparency is super glitchy
(Source code and problem line at the bottom) I made a simple program to load a transparent PNG onto SDL2. However, it pops up as the image, with a very glitchy background that keeps flashing. I suspect this is a problem with my graphics card (M2 Macbook Air), but I do not know how to fix this. I think this because the issue goes away after I disable hardware acceleration when creating my SDL renderer. // Issue goes away if I change the '0' in this line to SDL_RENDERER_SOFTWARE SDL_Renderer * renderer = SDL_CreateRenderer(window, -1, 0); My full source code can be found at https://pastebin.com/XqRxXmyt. My compile command can also be found at https://pastebin.com/a3YbGnLN (I am statically linking my program). How can I fix this transparency issue?
Found a solution. Not sure why it solves the problem, but simply clearing the screen before drawing the texture fixes everything: while (is_running){ // Game loop stuff SDL_RenderClear(renderer); // Draw stuff... }
73,298,903
73,299,103
Default value for template parameter, followed by non-type parameter pack
I'm struggling to make this code work template <typename T, typename U = int, auto... Params> class Foo {}; int main() { auto foo1 = Foo<int, int, 1, 2, 3>{}; auto foo2 = Foo<int, 1, 2, 3>{}; // I want it to compile } It looks like I need some hack. I tried partial specialization, but it doesn't work either template <typename T, typename U, auto... Params> class Foo {}; template <typename T, auto... Params> class Foo<T, int, Params...> {}; int main() { auto foo1 = Foo<int, int, 1, 2, 3>{}; auto foo2 = Foo<int, 1, 2, 3>{}; // I want it to compile } I can't find anything closely related to this, help pls :)
Unfortunately due to the way that template deduction works, this is ...not going to work. Here's one alternative approach where the first template parameter is always a tuple, with one or two types, with the second type defaulting to an int: #include <tuple> template<typename T, auto ...Params> class Foo; template<typename T, typename U, auto ...Params> class Foo< std::tuple<T, U>, Params...> { // Your template goes here, making use of T and U }; template<typename T, auto ...Params> class Foo< std::tuple<T>, Params...> : Foo<std::tuple<T, int>, Params...> { // Might need to define some cleanups here, like a delegating constructor, // and/or delegated overload operators. }; Foo<std::tuple<char>, 3, 4> defaulted; Foo<std::tuple<char, float>, 3, 4> non_defaulted; With a little bit more elbow grease it should be possible to require a formal std::tuple only when the 2nd optional type needs to be specified, and just specify the primary type directly (although that will create some avoidable confusion if the primary type is a std::tuple, itself).
73,299,054
73,299,146
GCC vs. Clang on the lifetime of temporary bound to an rvalue reference of another temporary
I want to figure out the lifetime of a temporary object S{} bound to an rvalue reference inside struct wrap<T>. wrap<T>::f() is a function that potentially interacts with the temporary; therefore, S{} must be alive when wrap<T>::f() is called. I consider two cases: (1) wrap{S{}}.f(); and (2) auto w = wrap{S{}}; w.f();. I am confident the first case should not result in any dangling references because S{} is destroyed only after the entire expression is evaluated. However, for the second case, I am not really certain. I hypothesized that the lifetime of the temporary should match the lifetime of w. To test my hypothesis, I wrote the following code snippet (also available on Compiler Explorer): #include <stdio.h> struct S { S() { puts("S::S()"); } ~S() { puts("S::~S()"); } }; template <typename T> struct wrap { T &&t; void f() { puts("wrap<T>::f()"); } }; template <typename T> wrap(T &&) -> wrap<T>; int main() { #if defined(_MSC_VER) puts("msvc"); #elif defined(__clang__) puts("clang"); #else // gnu puts("gcc"); #endif puts("== first =="); wrap{S{}}.f(); puts("== second =="); auto w = wrap{S{}}; w.f(); return 0; } It seems like there is a disagreement among the compilers: For x86-64 GCC 12.1 with -std=c++20: gcc == first == S::S() wrap<T>::f() S::~S() == second == S::S() wrap<T>::f() S::~S() For x86-64 clang (trunk) with -std=c++20: clang == first == S::S() wrap<T>::f() S::~S() == second == S::S() S::~S() wrap<T>::f() And, finally, x64 msvc v19.latest with /std:c++latest: msvc == first == S::S() wrap<T>::f() S::~S() == second == S::S() wrap<T>::f() S::~S() GCC and MSVC extend the lifetime of the temporary object, whereas clang does not. Which behavior is correct according to the standard?
clang is incorrect: both examples are valid and within lifetimes. The rule is that temporaries bound to references live as long as the reference (with some exceptions that don't apply here). Note that: auto w = wrap{S{}}; is exactly equivalent to: wrap<S> w{S{}}; And list-initialization directly binds (as opposed to parentheses). There is even an example in the standard that is basically exactly this, in [class.temporary]: struct S { const int& m; }; const S& s = S{1}; // both S and int temporaries have lifetime of s
73,299,413
73,314,797
Change service systemd status from it's code
I have a C++ programm and it has two runtime states: active and waiting. I want to be able to change systemd status of the corresponding server (systemctl status) from the code. I have seen that there are "active (running)" and "active (waiting)" statuses in systemd. Is there any opportunity to do it? Or at least when exactly are this systemd statuses set?
Those are systemd unit states and systemd manages them on its own, you can't directly set them. They are independent of the runtime states of your program. According to the systemctl manual, the state has three parts: load state (e.g. loaded, not-found) general unit state (e.g. acitve, inactive, failed) substate (e.g. running, waiting): the unit-type-specific detailed state of the unit, possible values vary by unit type The waiting state means the unit is waiting for an event. As of now, only automount, path and timer units have a waiting state.
73,299,810
73,300,022
Is there a way to open a new terminal window with code in C++?
I have an application and I want it to somehow open a new command line window for input. Is there a way to do this with C++?
I'm not sure what is your "application" in this case. However, for applications to interact with each other, usually we would need some kind of APIs (Application Programming Interface), so that what you have on another application (a new terminal as you said) could be properly used in the "main" application. If your desired result is just to get another terminal opened, we just have to call it. But remember, every Operating System has its own way to open a terminal, so if you like to automate everything, we have to use macros to check to current OS of the user, here is a suggestion: #include <cstdlib> int main() { #ifdef _WIN32 std::system("start program.exe"); // program.exe is app you have built to get input. #endif #ifdef _WIN64 std::system("start program.exe"); #endif #ifdef __APPLE__ std::system("open program"); #endif #ifdef __linux__ std::system("open program"); #endif // #ifdef and #endif are just like if - statement. } Every compiler has the macros like _WIN32-stands for windows 32bit, _WIN64-windows 64bit, and so on. Its pretty handy to use them. Hope this helps!
73,300,085
73,300,126
i would like to know why my getName function isn't working
#include <iostream> #include <optional> using namespace std; void myFunction(optional<string> name = nullopt) { if (name == nullopt) { cout << "I wish I knew your name!" << endl; } else { cout << "Hello " << name.value() << "!" << endl; } } void getName(string Name){ cout << "input name: " << endl; cin >> Name; } int main() { myFunction(); getName(); myFunction(Name); return 0; } what would i do to make the getName function working ive tried a few things like adding a string as such string Name = getName() but it wasnt working either.
You could just create a function with a return value instead.. #include <iostream> #include <optional> #include <string> using namespace std; void myFunction(optional<string> name = nullopt) { if (name == nullopt) { cout << "I wish I knew your name!" << endl; } else { cout << "Hello " << name.value() << "!" << endl; } } string getName(){ string Name; cout << "input name: " << endl; cin >> Name; return Name; } int main() { myFunction(); myFunction(getName()); return 0; }
73,300,532
73,300,922
Linked List segmentation fault, class
Wrote this program in Cpp for Linked Lists. I am getting an error in insert when trying to insert at the front of the linked list as a segmentation fault. I couldn't print the list with list.printList(), but if I use push_back() and then printList(), it works fine. Spent a lot of time pondering but couldn't figure out? Please help me! #include<iostream> using namespace std; class Node { private: int data; Node* next; public: Node() { data = 0; next = NULL; } void setData(int data) { this->data = data; } int getData() { return data; } void setNextNode(Node* node) { this->next = node; } Node* getNextNode() { return next; } }; class LinkedList { private: Node Head_node; public: void createList(int n) { int x; cin >> x; Head_node.setData(x); n--; while (n) { cin >> x; push_back(x); n--; } } Node* lastNode() { Node* temp = &Head_node; while ( (*temp).getNextNode() != NULL) //while is not last node { temp = (*temp).getNextNode(); } return temp; } void push_back(int x) { Node* temp = lastNode(); //move to last node Node* a = new Node; // create a new node (*temp).setNextNode(a); //link new node to list (*a).setData(x); //set new node data } void push_front(int x) { Node* a = new Node; (*a).setData(x); Node join = Head_node; (*a).setNextNode(&join); this->Head_node = (*a); } void printList() { Node* temp = &Head_node; do { cout << (*temp).getData() << " "; temp = (*temp).getNextNode(); } while (temp != NULL); } }; int main() { int n; cin >> n; LinkedList list; list.createList(n); list.push_front(29); list.printList(); return 0; } I ran code and it said "segmentation fault" But if I run list.push_back(29); list.printList(); instead, everything is still fine!
The root cause of the segmentation violation lies in the following lines: Node join = Head_node; (*a).setNextNode(&join); this->Head_node = (*a); You are storing the address of the function local variable join in the linked list. When the function returns, the pointer becomes a dangling pointer. Accessing that pointer causes undefined behavior. In your case, that manifests as segmentation violation. One way to resolve the problem will be: Create a new Node that stores the data of Head_node. Change the data of Head_node to store the new data. Make sure that the "next" pointers are adjusted accordingly. The following updated version of the function works for me. void push_front(int x) { Node* headCopy = new Node; headCopy->setData(Head_node.getData()); headCopy->setNextNode(Head_node.getNextNode()); Head_node.setNextNode(headCopy); Head_node.setData(x); }
73,300,768
73,301,125
Get number of tests ran by GoogleTest / fail on 0 tests run?
I'm using cmake's test runner to run several googletest test binaries. What I want to have happen is if a googletest test binary runs 0 tests via RUN_ALL_TESTS(), it fails. Currently, RUN_ALL_TESTS() returns success when it runs 0 tests. Alternatively, if I could somehow access the number of tests that RUN_ALL_TESTS() ran, I could override its success to be an error and bubble up the error instead. I've tried fixing this at the cmake level, with --no-tests=error. This doesn't work, however. I think the reason is the cmake sees itself running googletest test binaries, and those count as "running tests", even though the test binaries themselves don't have any tests. Alternatively it could be because some of the googletest test binaries have tests, the --no-tests=error parameter isn't triggering. I've looked into googletest, and none of the flags listed here seem to help https://google.github.io/googletest/advanced.html . I don't see a way to set options, RUN_ALL_TESTS doesn't return any other information, and I don't see a function to get # of tests runs. What options am I missing?.
To fail cmake test runner is easy. #include <gtest/gtest.h> int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); const int rv = RUN_ALL_TESTS(); if (rv != 0) return rv; #if 1 if (::testing::UnitTest::GetInstance()->test_to_run_count() == 0) return 1; #else if (::testing::UnitTest::GetInstance()->successful_test_count() == 0) return 1; #endif return 0; }
73,300,799
73,300,898
After about a minute, my openGL app freezes and "D3D12: Removing Device." is printed to the console
I am working on a simple openGL based (voxel) engine, and performing a lot of updates per frame to some vertex and buffer data. After about a minute or so of running, the screen freezes and D3D12: Removing Device. is printed to the console. The engine is pretty large, but i'll provide some of the important sudo code below. #include "sim.hpp" int main() { Engine *engine = new Engine(); do { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); engine->tick(voxelData); glfwSwapBuffers(engine->getWindow()); glfwPollEvents(); } while (glfwGetKey(engine->getWindow(), GLFW_KEY_ESCAPE) != GLFW_PRESS && glfwWindowShouldClose(engine->getWindow()) == 0); } Above is my main file. In engine->tick(), the following is called: calculateDeltaTime(); camera->update(deltaTime); world->setVoxelData(voxelData); renderer->buildBuffer(*world); renderer->render(*world, *shaderManager, *camera, glm::mat4(1)); Most importantly, in buildBuffer(), voxel data is grabbed from the world object and a bunch of buffers and vertex arrays are created. void Renderer::buildBuffer(World &world) { glGenVertexArrays(1, &_vertexArrayId); glBindVertexArray(_vertexArrayId); const GLfloat *vertices = &(world.getVertices()[0]); const GLfloat *colors = &(world.getColors()[0]); const GLfloat *normals = &(world.getNormals()[0]); _numberOfVertices = static_cast<GLsizei>(world.getVertices().size()); GLsizeiptr vertexSize = _numberOfVertices * sizeof(GLfloat); glGenBuffers(1, &_vertexBuffer); glBindBuffer(GL_ARRAY_BUFFER, _vertexBuffer); glBufferData(GL_ARRAY_BUFFER, vertexSize, vertices, GL_STATIC_DRAW); GLsizeiptr colorSize = world.getColors().size() * sizeof(GLfloat); glGenBuffers(1, &_colorBuffer); glBindBuffer(GL_ARRAY_BUFFER, _colorBuffer); glBufferData(GL_ARRAY_BUFFER, colorSize, colors, GL_STATIC_DRAW); GLsizeiptr normalsSize = world.getNormals().size() * sizeof(GLfloat); glGenBuffers(1, &_normalBuffer); glBindBuffer(GL_ARRAY_BUFFER, _normalBuffer); glBufferData(GL_ARRAY_BUFFER, normalsSize, normals, GL_STATIC_DRAW); } In the render function, the shaders are given certain parameters, and the buffers are bound and drawn. Any ideas on a fix for this? Thanks!
I figured out the issue. I was calling buildBuffeer every tick, but never deleted previously created buffers. This caused my PC to run out of memory (at one point openGL was using 8GB of memory...). With a simple check, I was able to delete the buffer using the glDeleteVertexArrays function.
73,301,766
73,301,993
Can object’s property be used, if object used in another thread?
Can the example below make undefined behavior and crash when main thread try to call SetX, because, although x property is not being accessed in new thread, but object itself is? class Object{ public: int x; int y; Object(int x, int y) { this->x = x; this->y = y; } void SetX(int x) { this->x = x; } }*object = nullptr; int *value_only = nullptr; void ch() { while(true) // assume there is some mechanism to quit loop { //with obj variable //readonly auto link = obj; auto y = obj->y; //write obj->y = 5; //without obj variable //read auto yy = *value_only; //write *value_only = 2; // note that obj->x is not touched } } int main() { obj = new Object(1,2); value_only = &obj->y; thread th(ch); obj->SetX(4); // assume, th termination is handled return 0; }
No there is no issue with accessing two different members of the same object. Note that both members are public and the setter doesn't do anything but set the member. Hence, you could rewrite ch to take a reference to obj->y as parameter and also in main, rather than calling SetX it could use int& x = obj->x;. Maybe then it is more obvious that the two threads do not actually share data. In the thread you copy obj but that merely copies the pointer. However, your program will crash due to not joining the thread. std::thread calls std::terminate when not joined (or detached) in its destructor. In any case you leak the memory of obj. While leaking memory on return from main is not a big deal, obj may manage other resources (files, db connections, etc) that need to be properly closed in the destructor.
73,302,632
73,307,811
How to save high score in c++?
I create a small car game. But I can't save high score which is used next time when I play game again . So that I compare score. I using c++ language and #include<graphics.h> header file? Please help me? How to save score in graphics mode?
for me an easy solution is, as others users told to you, to store it using the file system, so the next time you need to get the highest score you can take it with ease, let me write you an example: #include<fstream> using namespace std; fstream fs; fs.open("score.txt",iOS::app);//ios::app is to append the text to the end of the file fs<<[new highest score]; fs.close(); In case you only want to save one record, open the file using trunc to erase all elements and then you can write it down : void clear_file(std::string path){ fstream fs; fs.open(path, ios::trunc); fs.close(); } Check Cplusplus fstream for further information, hope it helps you out
73,302,872
73,303,253
Cmake install nested static library target_link_library undefined reference
Install nested static library, and target_link_library not working File structure: HelloLib WorldLib CMakeLists.txt WorldLib.cpp WorldLib.h CMakeLists.txt HelloLib.cpp HelloLib.h CMakeLists.txt main.cpp main.cpp #include <iostream> #include "HelloLib/HelloLib.h" int main() { std::cout << hello() << std::endl; return 0; } CMakeLists.txt (root) cmake_minimum_required(VERSION 3.16.3) project(HelloWorld) add_executable(${PROJECT_NAME} main.cpp) add_subdirectory(HelloLib) target_link_libraries( ${PROJECT_NAME} HelloLib ) HelloLib.cpp #include <string> #include "WorldLib/WorldLib.h" std::string hello() { return "Hello " + world(); } HelloLib.h #pragma once #include <string> std::string hello(); CMakeLists.txt (HelloLib) add_library(HelloLib HelloLib.cpp) add_subdirectory(WorldLib) target_link_libraries( HelloLib WorldLib ) WorldLib.cpp #include <string> std::string world() { return "World!"; } WorldLib.h #pragma once #include <string> std::string world(); CMakeLists.txt (WorldLib) add_library(WorldLib WorldLib.cpp) Build and run, successfully print out Hello World! Now I would like to make HelloLib as static library Change CMakeLists.txt (HelloLib), install to /usr/lib and /usr/include add_library(HelloLib HelloLib.cpp) add_subdirectory(WorldLib) target_link_libraries( HelloLib WorldLib ) install( TARGETS HelloLib ARCHIVE DESTINATION lib ) install( DIRECTORY "${CMAKE_SOURCE_DIR}/" # source directory DESTINATION "include" # target directory FILES_MATCHING # install only matched files PATTERN "*.h" # select header files ) Run (make install) (CMAKE_INSTALL_PREFIX=/usr) mkdir -p out/build cmake -S src -B out/build -DCMAKE_INSTALL_PREFIX=/usr cd out/build make make install [ 33%] Built target WorldLib [ 66%] Built target HelloLib [100%] Built target HelloWorld Install the project... -- Install configuration: "" -- Installing: /usr/lib/libHelloLib.a -- Up-to-date: /usr/include -- Installing: /usr/include/HelloLib -- Installing: /usr/include/HelloLib/HelloLib.h -- Installing: /usr/include/HelloLib/WorldLib -- Installing: /usr/include/HelloLib/WorldLib/WorldLib.h Static library (.a) should generate to /usr/lib/libHelloLib.a Let's test it, change CMakeLists.txt (root) cmake_minimum_required(VERSION 3.16.3) project(HelloWorld) add_executable(${PROJECT_NAME} main.cpp) add_subdirectory(HelloLib) target_link_libraries( ${PROJECT_NAME} /usr/lib/libHelloLib.a ) Then build, it give undefined reference error /bin/ld: /usr/lib/libHelloLib.a(HelloLib.cpp.o): in function `hello[abi:cxx11]()': HelloLib.cpp:(.text+0x20): undefined reference to `world[abi:cxx11]()' What's wrong with me? This can be successful with no nested library What is the correct way to install nested static library?
The issue here is not the install process but the fact that you link only to libHelloLib.a. Your libHelloLib.a need the symbol in libWorldLib.a because libHelloLib.a is a static lib and so only contains its own symbol. It does not contains the symbol world that is defined in libWorldLib.a. To make your project works, you need to install WorldLib and HelloLib and links against this two lib. target_link_libraries( ${PROJECT_NAME} HelloLib WorldLib ) Or you can change HelloLib into a shared library. This way the libHelloLib.so will also contains the symbol of WorldLib. You can also look at this Exported Target. It's an install command that will create some FindXX.cmake file that you will be able to use with the find_package command. You also will be able to defined the dependency of your lib. But if you want that HelloLib stay a static library you will have to install WorldLib
73,303,037
73,304,910
Why can mutex be used in different threads?
Using (writing) same variable in multiple threads simultaneously causes undefined behavior and crashes. Why using mutex, despite on fact that they are also variables, not causes undefined behavior? If mutex somehow can be used simultaneously, why not make all variables work simultaneously without locking? All my research is pressing Show definition on mutex::lock in Visual Studio, where I get at the end _Mtx_lock function without realization, and then I found it’s realization (Windows), though it has some functions also without realization: int _Mtx_lock(_Mtx_t mtx) { /* lock mutex */ return (mtx_do_lock(mtx, 0)); } static int mtx_do_lock(_Mtx_t mtx, const xtime *target) { /* lock mutex */ if ((mtx->type & ~_Mtx_recursive) == _Mtx_plain) { /* set the lock */ if (mtx->thread_id != static_cast<long>(GetCurrentThreadId())) { /* not current thread, do lock */ mtx->_get_cs()->lock(); mtx->thread_id = static_cast<long>(GetCurrentThreadId()); } ++mtx->count; return (_Thrd_success); } else { /* handle timed or recursive mutex */ int res = WAIT_TIMEOUT; if (target == 0) { /* no target --> plain wait (i.e. infinite timeout) */ if (mtx->thread_id != static_cast<long>(GetCurrentThreadId())) mtx->_get_cs()->lock(); res = WAIT_OBJECT_0; } else if (target->sec < 0 || target->sec == 0 && target->nsec <= 0) { /* target time <= 0 --> plain trylock or timed wait for */ /* time that has passed; try to lock with 0 timeout */ if (mtx->thread_id != static_cast<long>(GetCurrentThreadId())) { /* not this thread, lock it */ if (mtx->_get_cs()->try_lock()) res = WAIT_OBJECT_0; else res = WAIT_TIMEOUT; } else res = WAIT_OBJECT_0; } else { /* check timeout */ xtime now; xtime_get(&now, TIME_UTC); while (now.sec < target->sec || now.sec == target->sec && now.nsec < target->nsec) { /* time has not expired */ if (mtx->thread_id == static_cast<long>(GetCurrentThreadId()) || mtx->_get_cs()->try_lock_for( _Xtime_diff_to_millis2(target, &now))) { /* stop waiting */ res = WAIT_OBJECT_0; break; } else res = WAIT_TIMEOUT; xtime_get(&now, TIME_UTC); } } if (res != WAIT_OBJECT_0 && res != WAIT_ABANDONED) ; else if (1 < ++mtx->count) { /* check count */ if ((mtx->type & _Mtx_recursive) != _Mtx_recursive) { /* not recursive, fixup count */ --mtx->count; res = WAIT_TIMEOUT; } } else mtx->thread_id = static_cast<long>(GetCurrentThreadId()); switch (res) { case WAIT_OBJECT_0: case WAIT_ABANDONED: return (_Thrd_success); case WAIT_TIMEOUT: if (target == 0 || (target->sec == 0 && target->nsec == 0)) return (_Thrd_busy); else return (_Thrd_timedout); default: return (_Thrd_error); } } } So, according to this code, and the atomic_ keywords I think mutex can be written the next way: atomic_bool state = false; void lock() { if(!state) state = true; else while(state){} } void unlock() { state = false; } bool try_lock() { if(!state) state = true; else return false; return true; }
As you have found, std::mutex is thread-safe because it uses atomic operations. It can be reproduced with std::atomic_bool. Using atomic variables from multiple thread is not undefined behavior, because that is the purpose of those variables. From C++ standard (emphasis mine): The execution of a program contains a data race if it contains two conflicting actions in different threads, at least one of which is not atomic, and neither happens before the other. Any such data race results in undefined behavior. Atomic variables are implemented using atomic operations of the CPU. This is not implemented for non-atomic variables, because those operations take longer time to execute and would be useless if the variables are only used in one thread. Your example is not thread-safe: void lock() { if(!state) state = true; else while(state){} } If two threads are checking if(!state) simultaneously, it is possible that both enter the if section, and both threads believe they have the ownership: Thread 1 Thread 2 if (!state) if (!state) state=true; state=true; You must use an atomic exchange function to ensure that the another thread cannot come in between checking the value and changing it. void lock() { bool expected; do { expected = false; } while (!state.compare_exchange_weak(expected, true)); } You can also add a counter and give time for other threads to execute if the wait takes a long time: void lock() { bool expected; size_t counter = 0; do { expected = false; if (counter > 100) { Sleep(10); } else if (counter > 20) { Sleep(5); } else if (counter > 3) { Sleep(1); } counter++; } while (!state.compare_exchange_weak(expected, true)); }
73,303,179
73,322,124
C++ is quite slower than python in opencv
startTime = time.time() blob = cv2.dnn.blobFromImage(img, float(1.0/255.0), (frameWidth,frameHeight), (0,0,0), swapRB = True, crop = False) yolo.setInput(blob) layerOutput = yolo.forward(outputLayers) endTime = time.time() Python code that I am measuring the time auto start = chrono::steady_clock::now(); blob = blobFromImage(images[i], 1.0f/255.0f, Size(frameWidth, frameHeight), Scalar(0,0,0), true, false); net.setInput(blob); net.forward(layerOutput, getOutputsNames(net)); auto end = chrono::steady_clock::now(); C++ code that I am measuring time In C++: blob is Mat type, layerOutput is vector<Mat> type, getOutputsNames returns in vector<string> names. In python: blob is numpy.ndarray type, layerOutput is tuple type, outputLayers is a list type object. Both backends and targets are the same and backend is opencv, target is cpu, and I am using same yolov4 weight and config files in the same directories When measuring the time, it takes ~180-200 ms in python, yet in C++ it takes ~220-250 ms. Since C++ is a compiled language, I expect C++ to be work quite fast than the python, which is not the case surprisingly. What might be the reason that python works faster than the C++? Also what are your solutions to this? Thanks in advance!
I figured what the problem is, I have customized OpenCV for c++ to gain advantage of the CUDA cores in my Jetson Orin, yet the python uses general OpenCV stored in other directory, which doesn't have CUDA support. When I changed the OpenCV compilation for C++ to the general one, it worked fast as expected since in my customized compilation I also customized the CPU parallelization which seems to be slower than the default one.
73,303,443
73,649,108
Need help in plotting coordinates from a nested vector using gnuplot. Also, plotting a Hough transformation with Gnuplot
Good day I have implemented Gnuplot 5.4 in my Visual Studio 2019 Community edition. Through a sample program, I can successfully print the content of an STL vector. Now the question arises whether it is possible to display a nested vector with X,Y value pairs? constexpr int WIDTH = 2; constexpr int LENGTH = 1280; vector<vector<double> > vector_2d(LENGTH, vector<double>(WIDTH, 0)); In my example, randomly generated values are described at fixed X-positions, which are added up by a for-loop. In my case, however, the X-values do not have a fixed distance to each other, so I have to map them individually and cannot work with a for-loop. The following is an excerpt from my recorded values -2.73414564 -2.81298971 -1.95063043 -300.00000000 -2.66365290 -3.08498740 -2.62452888 -2.99414206 -2.58396339 -2.81281424 -2.54788446 -2.90335822 -2.51031804 -2.90331340 -1.77885580 -300.00000000 -1.75022638 -300.00000000 -2.39761853 -2.90317917 In the further course, a Hough transformation is also to be displayed in another Gnuplot window. For this, I iterate through a nested For loop in which I perform a calculation. This calculation (result is a sine curve in the Hough sapce) is to be displayed. float rho, cos_theta, sin_theta; for (int ti = 0; ti < n_theta; ti++) { cos_theta = static_cast<float>(cos(theta)); sin_theta = static_cast<float>(sin(theta)); for (long i = 0; i < arrIndex; i++) { rho = vector_2d[i][0] * cos_theta + vector_2d[i][1] * sin_theta; } } theta += q_theta; } n_theta describes the number of passes for all angles from 0 to 180 degrees. q_theta specifies the angle which is added up (quantisation). arrIndex describes the index in the vector. Perhaps someone can answer the question of whether it is possible to display the Hough transformation in real time. If this is not relatively easy to solve, whether and how the Hough space is to be represented after all calculations. So far I have not found a suitable solution. I would be very grateful for help Many greetings
If anyone comes across this post I have the following solution. To visualise the Hough transform, I write every tenth theta and rho value of the Hough transform for a pair of X-Y values in a text document. This is done 18 times per X-Y value pair. fstream outputFile5; outputFile5.open("C:\\(...)", ios::out); outputFile5.setf(ios::fixed); outputFile5.precision(8); //ArrIndex describes the number of X-Y values in the array (number of edge points) for (long i = 0; i < arrIndex; i++) { //Hough-Transform from -90° to 90° float theta = static_cast<float>(-M_PI / 2); for (int k = 0; k < n_theta; k++) { /*performing Hough-Transform*/ } //needed to separate the data sets if (k == 0) { outputFile5 << endl << endl << "Punkt " << i << endl; } if (k % 10 == 0) { outputFile5 << theta << " " << rho << endl; } theta += q_theta; } Then, with the help of the text file and the following code, the Hough Space is displayed. gp << "set grid\n "; gp << "set xlabel 'Theta'\n "; gp << "set ylabel 'Rho'\n "; gp << "set terminal wxt 0 size 790,800 position 500,100\n "; gp << "set term wxt title 'Windowname'\n "; gp << "set object circle at first " << acc_max_theta << "," << acc_max_rho << "radius char 0.7 fillstyle empty border lc rgb 'red' lw 3 front \n "; gp << "plot for [IDX=0:" << arrIndex << "]'C:/Users/pathname/' i IDX u 1:2 notitle with lines;pause mouse close\n "; gp << "unset object\n "; Point Cloud Hough-Transform
73,303,581
73,303,923
Check if pubkey belongs to twisted Edwards25519
I want to check if some pubkey belongs to twisted edwards25519 (I guess this is used for ed25519 ?) The problem is that I have in theory some valid pubkeys like: hash_hex = "3afe3342f7192e52e25ebc07ec77c22a8f2d1ba4ead93be774f5e4db918d82a0" or hash_hex = "fd739be0e59c072096693b83f67fb2a7fd4e4b487e040c5b128ff602504e6c72" and to check if they are valid I use from libsodium: auto result = crypto_core_ed25519_is_valid_point(reinterpret_cast<const unsigned char*>(hash_hex.c_str())); and the thing is that for those pubkeys which should be in theory valid, I have in both cases 0 as a result, which means that checks didn't pass (according to https://doc.libsodium.org/advanced/point-arithmetic#point-validation). So my question is if I am using this function wrong ? should that key be delivered in another form ? or maybe somehow those keys are not valid for some reasons (I have them from some coin explorer, so in theory they should be valid) ? is there some online tool where I can check if those pubkey belongs to that eliptic curve ?
You need to convert your hex string into binary format. Internally, the ed25519 functions work on a 256 (crypto_core_ed25519_BYTES (32) * 8) bit unsigned integer. You can compare it with an uint64_t, which consists of 8 octets. The only difference is that there is no standard uint256_t type, so a pointer to an array of 32 unsigned char is used instead. I use std::uint8_t instead of unsigned char below, so if std::uint8_t is not an alias for unsigned char the program should fail to compile. Converting the hex string to binary format is done like this. A nibble is 4 bits, which is what a single hex digit can represent. 0 = 0b0000 and f = 0b1111. You lookup each hex character in a lookup table to easily convert the character into the value 0 - 15 (decimal), 0b0000 - 0b1111 (binary). Since an uint8_t requires two nibbles, you combine them two and two. The first nibble is left shifted to form the high part of the final uint8_t and the second nibble is just bitwise OR:ed (|) with that result. Using fe as an example: f = 0b1111 e = 0b1110 shift f left 4 steps: f0 = 0b11110000 bitwise OR with e 0b11110000 | 0b00001110 ------------ 0b11111110 = 254 (dec) Example: #include <sodium.h> #include <cstdint> #include <iostream> #include <string_view> #include <vector> // a function to convert a hex string into binary format std::vector<std::uint8_t> str2bin(std::string_view hash_hex) { static constexpr std::string_view tab = "0123456789abcdef"; std::vector<std::uint8_t> res(crypto_core_ed25519_BYTES); if(hash_hex.size() == crypto_core_ed25519_BYTES * 2) { for(size_t i = 0; i < res.size(); ++i) { // find the first nibble and left shift it 4 steps, then find the // second nibble and do a bitwise OR to combine them: res[i] = tab.find(hash_hex[i*2])<<4 | tab.find(hash_hex[i*2+1]); } } return res; } int main() { std::cout << std::boolalpha; for(auto hash_hex : { "3afe3342f7192e52e25ebc07ec77c22a8f2d1ba4ead93be774f5e4db918d82a0", "fd739be0e59c072096693b83f67fb2a7fd4e4b487e040c5b128ff602504e6c72", "this should fail" }) { auto bin = str2bin(hash_hex); bool result = crypto_core_ed25519_is_valid_point(bin.data()); std::cout << "is " << hash_hex << " ok: " << result << '\n'; } } Output: is 3afe3342f7192e52e25ebc07ec77c22a8f2d1ba4ead93be774f5e4db918d82a0 ok: true is fd739be0e59c072096693b83f67fb2a7fd4e4b487e040c5b128ff602504e6c72 ok: true is this should fail ok: false Also note: libsodium comes with helper functions to do this conversion between hex strings and binary format: char *sodium_bin2hex(char * const hex, const size_t hex_maxlen, const unsigned char * const bin, const size_t bin_len); int sodium_hex2bin(unsigned char * const bin, const size_t bin_maxlen, const char * const hex, const size_t hex_len, const char * const ignore, size_t * const bin_len, const char ** const hex_end);
73,303,801
73,312,352
Check if a different process is running with elevated privileges
I use 'elevated' here in the context of Windows UAC (i.e. Run as Administrator). Seemingly the standard way to check if a process is elevated is to use OpenProcess to get a handle to that process, then use OpenProcessToken to get an access token for that process, followed by GetTokenInformation() with the TokenElevation or TokenElevationType classes and finally checking the resultant info. However, OpenProcessToken requires the process handle to have the PROCESS_QUERY_INFORMATION permission, so ironically this check cannot be performed if the checking process is not elevated and the checked process is (as based on my testing trying to use OpenProcess in that circumstance results in an access denied error). One could presume this means that the process is elevated, but this isn't wholly correct as I believe another possibility for that outcome is simply that the process was started by another user. In many circumstances it may just be easier to attempt a needed action and look for an access denied error and go from there, but in one particular case I need to start an external application and I'd like to start it as an administrator depending on whether or not a third process is running as an administrator. Since in this case "just attempting what I want to do" is more involved that simply calling a function or two, I was hopping there might be a more direct way for a non-elevated process to check if another process is elevated (including when it is elevated, hilariously).
Thanks to RbMm (and Hantalyte indirectly) I've been made aware that the Microsoft documentation for OpenProcessToken is incorrect in its assertion that the provided handle must have the PROCESS_QUERY_INFORMATION access permission, as it actually only requires that the handle have PROCESS_QUERY_LIMITED_INFORMATION (I have confirmed this with my own testing). It is possible to get a handle to an elevated process from within a non-elevated process with the permission PROCESS_QUERY_LIMITED_INFORMATION, as long as both were started from the same account, meaning that one can check other processes for elevation using the procedure in my question that I original though didn't work due to the errant documentation. As Hantalyte/RbMm point out, if the process being checked is owned by a different account the checking process needs the SE_DEBUG_NAME privilege to be enabled. Hopefully the MS docs should be corrected soon. UPDATE: The correction PR has been merged. UPDATE 2: The correction is now live: https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-openprocesstoken
73,303,868
73,304,226
static_assert not working inside class template definition
I'm trying to define a static member variable outside the class definition. It works as intended. But the static_assert that I placed inside the class definition does not compile for some reason. Why? The error message is: note: 'Foo<unsigned int>::var' was not initialized with a constant expression Commenting out the static_assert statement lets the code compile. The code (link): #include <iostream> #include <cstdint> #include <concepts> template < std::unsigned_integral size_type > class Foo { public: inline static const size_type var; static_assert( var <= 20, "Error" ); // note: 'Foo<unsigned int>::var' was not // initialized with a constant expression }; template <> inline constexpr std::uint32_t Foo<std::uint32_t>::var { 10 }; int main( ) { return Foo<std::uint32_t>::var; } Is there a way to fix this? Or should I place the static_assert outside the class definition and after the definition of Foo<T>::var? Note: I might have to mention that the reason for static_assert being inside the class body is to avoid code duplication. Otherwise, I would have to write that static assert statement after the definition of var for every instantiation of Foo<T>.
inline static const size_type var; That's all fine and dandy, but it does not mean that var is usable in a constant expression for every instantiation. There's the famous (infamous?) [temp.res.general]/8 The validity of a template may be checked prior to any instantiation. The program is ill-formed, no diagnostic required, if: a hypothetical instantiation of a template immediately following its definition would be ill-formed due to a construct that does not depend on a template parameter, or That's ill-formed NDR; but a compiler is allowed to check. A specialisation will not be available immediately following the primary definition, so while you may specialize to make the member constexpr, it doesn't save the primary template from running foul of this condition. I'd use a trait and invert the order. template<typename T> inline constexpr T FooSizeTraitValue = 10000; template<> constexpr std::uint32_t FooSizeTraitValue<std::uint32_t> = 10; template < std::unsigned_integral size_type > class Foo { public: static constexpr size_type var = FooSizeTraitValue<size_type>; static_assert( var <= 20, "Error" ); }; This should give you the same ability to specialise for different types as you wanted, without poisoning the body of the primary template unconditionally.
73,303,979
73,304,202
Code::Blocks returns -10737741819 (0xC0000005) when executing MySQL loop insert c++
I've been making program that need to continuously insert data to a database. I'm new to C++. I'm using xampp for my database. I want to make insert loop inside one of my function. my code looks like this #include "stdio.h" #include "fstream" #include "iostream" #include "mysql.h" #include "sstream" void loop(); void print(); int i; const char* hostname = "localhost"; const char* username = "root"; const char* password = ""; const char* database = "testinsertdb"; unsigned int port = 3306; const char* unixsocket = NULL; unsigned long clientflag = 0; insertion(){ MYSQL* conn; conn = mysql_init(0); conn = mysql_real_connect(conn, hostname, username, password, database, port, unixsocket, clientflag); int qstate=0; using namespace std; stringstream ss; ss << " INSERT INTO test (number) values ('" <<i<<"')"; string query = ss.str (); const char * q = query.c_str(); qstate = mysql_query(conn, q); if (qstate == 0) { cout <<" Record inserted successfully ..."<<endl; } else { cout <<" Error, data not inserted..."<<endl; } } int main() { print(); return 0; } void print() { for (int j = 0; j < 1000000; j++) { loop(); } } void loop() { i=1; insertion(); } When I run the program, I managed to insert some data to the database, but after several seconds the program stopped with code -10737741819 (0xC0000005). On my build log Process the terminated with status -1073741510 How can i solve this?
Preferablly try this one. Your code is trying to connect database as many times as the loop proceeds. There is the description of that error from this link #include "stdio.h" #include "fstream" #include "iostream" #include "mysql.h" #include "sstream" void loop(); void print(); MYSQL* conn; const char* hostname = "localhost"; const char* username = "root"; const char* password = ""; const char* database = "testinsertdb"; unsigned int port = 3306; const char* unixsocket = NULL; unsigned long clientflag = 0; void insertion() { int qstate=0, i; using namespace std; stringstream ss; ss << " INSERT INTO test (number) values ('" <<i<<"')"; string query = ss.str (); const char * q = query.c_str(); qstate = mysql_query(conn, q); if (qstate == 0) { cout <<" Record inserted successfully ..."<<endl; } else { cout <<" Error, data not inserted..."<<endl; } } int main() { print(); return 0; } void print() { conn = mysql_init(0); conn = mysql_real_connect(conn, hostname, username, password, database, port, unixsocket, clientflag); for (int j = 0; j < 1000000; j++) { loop(); mysql_close(conn); } void loop() { i=1; insertion(); }
73,304,347
73,304,663
c++20: how to move capture a class instance
I want to construct a factory function for a class B, which needs a callback. The factory function gives a lambda to B, but this lambda needs an instance of another class A, which I want to create inside of my factory and move into the lambda. A is not copyable but moveable, so I would expect that this should be possible. Unexpectedly, the compiler wants to use the deleted copy constructor of A rather than its move constructor (error: use of deleted function 'A::A(const A&)'). Minimum example: #include <functional> class A { public: A() {} A(const A &) = delete; A& operator=(const A &) = delete; A(A&&) noexcept {} }; class B { public: explicit B(std::function<void()>) { }; }; B b_factory() { auto a { A() }; return B { [a = std::move(a)]() { // do something with a } }; } B b = b_factory(); Compiler output: $ arm-poky-linux-gnueabi-g++ --version arm-poky-linux-gnueabi-g++ (GCC) 9.3.0 Copyright (C) 2019 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. $ arm-poky-linux-gnueabi-g++ -mfpu=neon -mfloat-abi=hard -mcpu=cortex-a9 -fstack-protector-strong -D_FORTIFY_SOURCE=2 -Wformat -Wformat-security -Werror=format-security --sysroot=/home/.../poky_sdk_toolchain/sysroots/cortexa9hf-neon-poky-linux-gnueabi --sysroot=/home/.../poky_sdk_toolchain/sysroots/cortexa9hf-neon-poky-linux-gnueabi -I../include -O2 -pipe -g -feliminate-unused-debug-types -g -Wall -Wextra -Werror -Wno-psabi -std=gnu++2a -MD -MT src/lib/CMakeFiles/traplog.dir/move_example.cpp.o -MF src/lib/CMakeFiles/traplog.dir/move_example.cpp.o.d -o src/lib/CMakeFiles/traplog.dir/move_example.cpp.o -c ../src/lib/move_example.cpp In file included from /home/.../poky_sdk_toolchain/sysroots/cortexa9hf-neon-poky-linux-gnueabi/usr/include/c++/9.3.0/functional:59, from ../src/lib/move_example.cpp:1: /home/.../poky_sdk_toolchain/sysroots/cortexa9hf-neon-poky-linux-gnueabi/usr/include/c++/9.3.0/bits/std_function.h: In instantiation of 'static void std::_Function_base::_Base_manager<_Functor>::_M_clone(std::_Any_data&, const std::_Any_data&, std::false_type) [with _Functor = b_factory()::<lambda()>; std::false_type = std::integral_constant<bool, false>]': /home/.../poky_sdk_toolchain/sysroots/cortexa9hf-neon-poky-linux-gnueabi/usr/include/c++/9.3.0/bits/std_function.h:211:16: required from 'static bool std::_Function_base::_Base_manager<_Functor>::_M_manager(std::_Any_data&, const std::_Any_data&, std::_Manager_operation) [with _Functor = b_factory()::<lambda()>]' /home/.../poky_sdk_toolchain/sysroots/cortexa9hf-neon-poky-linux-gnueabi/usr/include/c++/9.3.0/bits/std_function.h:677:19: required from 'std::function<_Res(_ArgTypes ...)>::function(_Functor) [with _Functor = b_factory()::<lambda()>; <template-parameter-2-2> = void; <template-parameter-2-3> = void; _Res = void; _ArgTypes = {}]' ../src/lib/move_example.cpp:27:5: required from here /home/.../poky_sdk_toolchain/sysroots/cortexa9hf-neon-poky-linux-gnueabi/usr/include/c++/9.3.0/bits/std_function.h:176:6: error: use of deleted function 'b_factory()::<lambda()>::<lambda>(const b_factory()::<lambda()>&)' 176 | new _Functor(*__source._M_access<const _Functor*>()); | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ../src/lib/move_example.cpp:24:26: note: 'b_factory()::<lambda()>::<lambda>(const b_factory()::<lambda()>&)' is implicitly deleted because the default definition would be ill-formed: 24 | [a = std::move(a)]() { | ^ ../src/lib/move_example.cpp:24:26: error: use of deleted function 'A::A(const A&)' ../src/lib/move_example.cpp:8:5: note: declared here 8 | A(const A &) = delete; | ^ Can somebody explain this? edit #1: added full build output edit #2: removed unneeded code
IMO, the reason is that the type lambda you passed to std::function ctor violate std::function type requirement, which needs the passed Callable must be CopyConstructible. Since the captured type A's copy constructor is deleted, it results that the lambda's copy constructor cannot be implicitly-declared. Here's some reference from cppreference page: Initializes the target with std::forward<F>(f). The target is of type std::decay<F>::type. If f is a null pointer to function, a null pointer to member, or an empty value of some std::function specialization, *this will be empty after the call. This constructor does not participate in overload resolution unless the target type is not same as function, and its lvalue is Callable for argument types Args... and return type R. The program is ill-formed if the target type is not copy-constructible or initialization of the target is ill-formed. Also from the same page: std::decay<F>::type must meet the requirements of Callable and CopyConstructible. Possible solution 1 If c++23 is acceptable to you, you can directly use std::move_only_function. https://godbolt.org/z/qhfd83955 Possible solution 2 You can write a custom naive function wrapper to handle your move only type, which is a simple type-erasure class with a function call operator, basically the same thing as chapter 9 of book "C++ Concurrency In Action": class TaskWrapper { struct impl_base { virtual void call() = 0; virtual ~impl_base() = default; }; std::unique_ptr<impl_base> impl; template <typename F> struct impl_type : impl_base { F f; impl_type(F&& f_) : f(std::move(f_)) {} void call() final { f(); } }; public: template <typename F> TaskWrapper(F&& f) : impl(new impl_type<F>(std::forward<F>(f))) {} void operator()() { impl->call(); } TaskWrapper() = default; TaskWrapper(TaskWrapper&& other) noexcept : impl(std::move(other.impl)) {} TaskWrapper& operator=(TaskWrapper&& other) noexcept { impl = std::move(other.impl); return *this; } TaskWrapper(const TaskWrapper&) = delete; TaskWrapper(TaskWrapper&) = delete; TaskWrapper& operator=(const TaskWrapper&) = delete; }; And change B signature to: class B { public: explicit B(TaskWrapper cb) { (void)(cb); }; }; Then use it like: B b_factory() { auto a { A() }; return B { TaskWrapper([a = std::move(a)]() { // do something with a }) }; }
73,304,543
73,305,787
I'm trying to write a char into a .txt file by using the ifstream getline function. But i get an Error Message
E0304 no instance of overloaded function "std::basic_ifstream<_Elem, _Traits>::getline [with _Elem=char, _Traits=std::char_traits]" matches the argument list Im using a struct for the Information: struct customer { int id; char name; char phone; char address; }; And im trying to write the Customers Information into a .txt file: void customerData() { ifstream ifs; ifs.open("Customer.txt"); int custNum = 0; while (!ifs.eof()) { ifs >> cust[custNum].id; ifs.ignore(); ifs.getline(cust[custNum].name, 100, ';'); ifs.getline(cust[custNum].phone, 15, ';'); ifs.getline(cust[custNum].id, 15, ';'); ifs.getline(cust[custNum].address, 1500); custNum++; } } I cant figure out how to fix the above posted Error on the getline functions.
There are big mistakes in your code that guys pointed out. You are not writing to the file, you are reading it. You cannot store a full name in a single character. Actually, if you want to store this data, you should use character array or std::string. So your struct will be like this : struct customer { int ID; char name[100]; char phone_number[15]; char address[1500]; /* OR int ID; std::string name; std::string phone_number; std::string address; in this case it's better to use std::string instead of using 1500 characters for address */ } Also, getline is not for writing to the file (as you said you want to write in file) , it is used for reading from the file. So your customerData function will look like this: // saving in file ofstream ofs(Customer.txt); // check if file is created if(ofs.is_open(){ ofs << name << '\n'; ofs << address << '\n'; ofs << phone_number << '\n'; ofs << id << '\n'; // This is a simple way to store data in a file. // There are other ways to store data in a file.. // I used this because you can use getline to read them and get the data as lines. }