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
74,081,089
74,116,547
How can I pass data in the JVM between the agent dll and a debugger GUI executable?
I want to design a native agent for the JVM via the Java Virtual Machine Tool Interface for C++. I want to also design a executable for the user to see what is going on within the JVM and this will be a GUI designed in C++ Qt. I setup a solution in Visual Studio with 2 projects: agent project JVMTI dll Qt EXE GUI project In the Qt project, I made sure to include the dll so that it can communicate between the GUI and JVM. However, I read that the DLL cannot contain shared variables so the code below doesnt work. For context, here is the agent dll source that the JVM attaches: #include "pch.h" #include "../include/jvmagent.h" JNIEXPORT jint JNICALL Agent_OnLoad(JavaVM* vm, char* options, void* reserved) { JVMAgent::agentOnLoad(vm); return JNI_OK; } __declspec(dllexport) long JVMAgent::agentOnLoad(JavaVM* vm) { JVMAgent::initialized = true; return JNI_OK; } The corresponding header for the JVM agent: #pragma once #ifndef DLLAGENT_H #define DLLAGENT_H #include "../src/pch.h" namespace JVMAgent { #pragma data_seg("SHARED") inline bool initialized = false; #pragma data_seg() #pragma comment(linker, "/section:SHARED,RWS") __declspec(dllexport) long agentOnLoad(JavaVM* vm); } #endif // DLLAGENT_H I tried to do some shared memory workarounds but it has not been working so far. The goal is to eventually communicate all the JVM functions and data to the executable code here: #include "stdafx.h" #include "debugvisualizer.h" #include "jvmagent.h" DebugVisualizer::DebugVisualizer(QWidget *parent) : QMainWindow(parent) { ui.setupUi(this); connect(ui.pushButton, SIGNAL(clicked(bool)), SLOT(onButtonPressed())); } void DebugVisualizer::onButtonPressed() { ui.textBrowser->setText(QVariant(JVMAgent::initialized).toString()); } The code above defines a pushbutton where when I press it, the JVM contents should display. So far, I cannot seem to find a way to make the two communicate. The web is sparse with JVMTI documentation with it often being outdated or for Linux, but I need to develop on Windows. Is there a way for this to happen since I have to pass the dll as an argument into the Qt executable. If all of this still doesn't make too much sense, here is what I am trying to accomplish (which does not work yet but is the goal): Start the JVM and load the agent. JVM calls Agent_OnLoad(JavaVM*, ...) from above. The agentOnLoad function will set a single boolean to true. The Qt executable includes the header and reads the boolean value. The Qt executable displays the updated boolean value. Again, I know that this is not possible because dll's cannot "share" variables across processses. I just want to know if there is another way of accomplishing above. Hopefully this is detailed enough.
In your scenario, there are two different processes: JVM with the agent library GUI executable To make them talk to each other, you need an IPC (inter-process communication) mechanism. The linked article lists all typical IPC approaches. Sockets, pipes or shared memory are the most common for a purpose like yours. For example, that's exactly how a Java debugger in IDE works: JVM starts with a jdwp agent attached, and IDE debugger talks to the agent via a socket connection using JDWP protocol.
74,081,768
74,082,223
How to merge two structs with same structure but different content?
I have two structs: struct DEF { DEF(std::string,double foo,double); ~DEF(); //---- theory's functions ----// double V_of_phi(double,double); double dV_of_phi(double, double); ... double metricStartingPoint; double scalarStartingPoint; ...} struct R2 { R2(std::string,double,double foo); ~R2(); //---- theory's functions ----// double V_of_phi(double,double); double dV_of_phi(double, double); ... double metricStartingPoint; double scalarStartingPoint; ...} These structs are used in a class which is templated with respect to which "theory" (struct) is used like this: template<class theoryType> class STT{ public: STT(String, double, double); ~STT(); private: theoryType* theory; //points to theory at study theoryType model; //theory model instance ... } and used like theory->V_of_phi(...) inside the class etc. At the moment I'm instantiating the model instance in the STT constructor like: template<class theoryType> STT<theoryType>::STT(String eos_name, double central_density, double coupling): model(eos_name,coupling,central_density), ... {} where coupling is only used in R2 struct and not in DEF (hence the foo in DEF's constructor) and vice versa for central_density which is only used in DEF. Besides the constructor, the two structs have the exact same structure but different content (for example DEF::V_of_phi is different than R2::V_of_phi). Is there any way to make this cleaner, instead of making two different structs that have the exact same format but different member function implementations and member variable values?
This cries for applying "strategy design pattern". Please read about it here, or in many available books about "design patterns". You would basically implement an abstract base class for the strategy and then derive the specific strategies from that. In your terminology this would be the equivalent of "theory". In the context class (in your example "STT"), you would add a pointer to the strategy's base class. Then you can call the needed functions using runtime polymorphism. In your example you are using static polymorphism using templates. Also possible. If you read the Wikipedia article, you could even use composition instead of inheritance. This has sometimes advantages and follows other OOP principles. But I do not know your requirements, so, I cannot tell. I made for you an extremely artificial example, to explain what I was writing above. As said, the question does not contain enough information to come up with a complete solution. Please see: #include <iostream> struct Strategy { virtual double V_of_phi(double, double) = 0; virtual double dV_of_phi(double, double) = 0; }; struct StrategyDEF : public Strategy { double V_of_phi(double a, double b) override { return 42 + a + b; } double dV_of_phi(double a, double b) override { return 42 - a -b; } }; struct StrategyR2 : public Strategy { double V_of_phi(double a, double b) override { return 42 + 2 * (a + b); } double dV_of_phi(double a, double b) override { return 42 - 2 * (a + b); ; } }; struct ContextSTT { Strategy* strategy{}; double metricStartingPoint{}; double scalarStartingPoint{}; double calculateV_of_phi() { return strategy->V_of_phi(metricStartingPoint, scalarStartingPoint); } double calculateDV_of_phi() { return strategy->dV_of_phi(metricStartingPoint, scalarStartingPoint); } }; int main() { StrategyDEF strategyDEF{}; StrategyR2 strategyR2{}; ContextSTT contextSTTWithDEF{ &strategyDEF, 1, 1}; ContextSTT contextSTTWithR2{ &strategyDEF, 2, 2 }; std::cout << contextSTTWithDEF.calculateV_of_phi() << '\t' << contextSTTWithDEF.calculateDV_of_phi() << '\n'; std::cout << contextSTTWithR2.calculateV_of_phi() << '\t' << contextSTTWithR2.calculateDV_of_phi() << '\n';
74,081,795
74,082,553
Why does my boost::interprocess shared memory string vector code trigger segfault?
I have the following minimally reproducible code of using several child processes to append strings to a shared vector. But at some executions, my prorgam either freezes or goes into segmentation fault when all the child process finish. At other times, it works with no issues. When the segfault does happen, it seems to take place when the parent process accesses the shared vector. Can anyone more experienced with boost help me debug please. ... namespace bip = boost::interprocess; typedef bip::managed_shared_memory msm; bip::shared_memory_object::remove("shmem_streak"); bip::managed_shared_memory shm(bip::open_or_create, "shmem_streak", 10000000); bip::allocator<char, msm::segment_manager> chr_altr(shm.get_segment_manager()); typedef bip::basic_string<char, char_traits<char>, decltype(chr_altr)> str; bip::allocator<str, msm::segment_manager> str_altr(shm.get_segment_manager()); typedef vector<str, decltype(str_altr)> vec; shm.construct<vector<str, decltype(str_altr)>>("res_vec")(str_altr); for (int i = 0, pid; i < num_procs; i++) { if ((pid = fork()) == 0) { bip::interprocess_mutex mutex; bip::scoped_lock<bip::interprocess_mutex> lock(mutex); auto child_res_vec = shm.find<vec>("res_vec").first; cout << " pushing " << i << " lock: " << endl; //<< lock << endl; str tmp_str(chr_altr); tmp_str = to_string(i).c_str(); child_res_vec->push_back(tmp_str); exit(0); } else cout << "pid: " << pid << " created" << endl; } while (wait(NULL) > 0) ; auto child_res_vec = shm.find<vec>("res_vec").first; cout << "test res pq: " << endl; for (auto elem : *child_res_vec) cout << elem << endl; cout << child_res_vec->back() << endl; ... here is the buggy output: pid: 91625 created pid: 91626 created pid: 91627 created pid: 91628 created pushing 1 lock: pushing 0 lock: pushing 2 lock: pushing 3 lock: pid: 91629 created pid: 91630 created pushing 4 lock: pid: 91631 created pushing 5 lock: pid: 91632 created pushing 6 lock: pid: 91633 created pushing 7 lock: pid: 91634 created pushing 8 lock: pid: 91635 created pushing 9 lock: pushing 10 lock: pid: 91636 created pushing 11 lock: test res pq: zsh: segmentation fault python app.py correct output: pid: 91819 created pushing 0 lock: pid: 91820 created pushing 1 lock: pid: 91821 created pushing 2 lock: pid: 91822 created pushing 3 lock: pid: 91823 created pushing 4 lock: pid: 91824 created pushing 5 lock: pushing 6 lock: pid: 91825 created pid: 91826 created pushing 7 lock: pid: 91827 created pushing 8 lock: pid: 91828 created pushing 9 lock: pushing 10 lock: pid: 91829 created pid: 91830 created pushing 11 lock: test res pq: 0 1 2 3 4 5 6 7 8 9 10 11
The problem is with the mutex. You are creating a new mutex for every process. You have to make sure there is a single mutex that is shared by all processes. Just moving the declaration of mutex outside the for-loop isn't enough though; the mutex has to be stored inside the shared memory segment for this to work, see the description of boost::interprocess::interprocess_mutex. Some other things to note: Prefer '\n' over std::endl. wait() can return -1 for other reasons than just that no child processes are left. Be sure to check that errno == ECHILD before exiting the while-loop. Use for(auto& elem: ...); the reference will avoid unnecessary copies of the elements being made.
74,081,887
74,082,011
Finding the most divisible number in a 100,000 range
I'm a student in the 10th grade and our teacher assigned some exercises. I'm pretty advanced in my class but one exercise is just isn't coming together as I want. The exercise is as follows: Given the numbers between 100,000 and 200,000, find the number with the most divisors (as in which number can be divided with the most numbers, any number). I wrote something but it executes in 32 seconds(!) and I just can't figure out the logic behind it (I can't even check if the answer is correct). This is the code that I wrote: void f3() { int mostcount = 0, most, divisors = 0; for (int i = 100000; i <= 200000; i++) { for (int j = 1; j<=i/2; j++) { if (i % j == 0) { divisors++; } } if (divisors > mostcount) { mostcount = divisors; most = i; } divisors = 0; } cout << most << endl; return; } The output: 166320 Edit: My question is how can I reduce the runtime? I'd be really thankful if you could explain your answer if you do decide to help, instead of just saying that I could do this with an XYZ type binary tree.
Using @AhmedAEK 's response: replace j<=i/2 with j<=sqrt(i), you only need to loop up to that, also #include <math.h> at the top, you also need to multiply the total divisors by 2, since there is a number above the sqrt that reflects the number below the sqrt. ie: 1000 is 10 x 100. void f3() { int mostcount = 0, most, divisors = 0; for (int i = 100000; i <= 200000; i++) { for (int j = 2; j<=sqrt(i); j++) { if (i % j == 0) { divisors++; } } if (divisors > mostcount) { mostcount = divisors; most = i; } divisors = 0; } cout << most << endl; return; }
74,081,911
74,082,065
swap 2 node in doubly linked list without swapping the data C++
Im trying to swap position of two node in doubly linked list without swapping the data, this is my code, it came up with wrong answer when run through this testcase: the list length: 20 the list: 2158 2398 300 2268 3655 765 3792 4038 1761 4762 1292 3200 3882 962 488 1938 3757 3122 302 640 positions to swap: 9 12 the right answer is: 2158 2398 300 2268 3655 765 3792 4038 3200 1292 4762 1761 3882 962 488 1938 3757 3122 302 640 but mine got a bit different:2158 2398 300 2268 3655 765 3792 4038 3200 4762 1292 1761 3882 962 488 1938 3757 3122 302 640. I need some help here /*struct ListNode { int val; ListNode *left; ListNode *right; ListNode(int x = 0, ListNode *l = nullptr, ListNode* r = nullptr) : val(x), left(l), right(r) {} }; */ ListNode* reverse(ListNode* head, int a, int b) { //To Do if(a==b) return head; ListNode* h = head; ListNode* anode = new ListNode; ListNode* bnode = new ListNode; int n(1); for(int i(1); h!= nullptr; i++){ if(i == a){ anode = h; } if(i == b){ bnode = h; // break; // now h = bnode } ++n; h= h->right; } ListNode* bleft = new ListNode; ListNode* bright = new ListNode; bright = bnode->right; bleft = bnode->left; bnode->right = anode->right; bnode->right->left = bnode; if(a==1){ } else{ bnode->left = anode->left; bnode->left->right = bnode; } anode->left = bleft; bleft->right = anode; if(bright ==nullptr){ anode->right = nullptr; } else{ anode->right = bright; bright->left = anode; } if(a==1) return bnode; return head; }
The right answer, as well as the name of the function you are supposed to write, suggest that you should reverse a sublist. Your code doesn't attempt to do that. It swaps positions of the first and the last nodes of the sublist. These are two different operations. The reverse operation generally needs a loop to iterate over the nodes of the sublist. On an unrelated note, you code has four totally useless new expressions. They contribute nothing but memory leaks. Just remove them.
74,082,118
74,082,148
What if template argument explicitly specified to be function type
I tried the code below (https://godbolt.org/z/rcfPK451M) bool cmp1(int &a, int &b) { return a < b; } template<typename T> struct S; template<typename T> void test(T cmp) { S<T> t; S<decltype(cmp)> s; } void foo() { test<decltype(cmp1)>(cmp1); } And got the following compile error <source>:5:10: error: 'S<bool(int&, int&)> t' has incomplete type 5 | S<T> t; | ^ <source>:6:22: error: 'S<bool (*)(int&, int&)> s' has incomplete type 6 | S<decltype(cmp)> s; | ^ Which shows that T is the type bool(int&, int&) and cmp has the type bool (*)(int&, int&). I'm confused why they have different types.
You are declaring a variable with that function type (the argument cmp), so the type decays into a function pointer type. You cannot have a variable with a function type, only a pointer to a function. The standard says [temp.deduct]/3: After this substitution is performed, the function parameter type adjustments described in 8.3.5 are per- formed. [ Example: A parameter type of “void ()(const int, int[5])” becomes “void()(int,int)”. — end example ] In short, this decaying happens because the variable is a parameter to a function template, and it happens after type deduction. It does not happen if you try decltype(cmp1) a = cmp1;, because decltype(cmp1) a actually declares a function, no decaying needs to happen (and then you can't assign to a function). In test, T is still the function type because you explicitly specify it with decltype(cmp1). Remove this, letting template argument deduction happen, and you can see it gets deduced to the decayed type (since that's the actual type of the argument cmp). It's the same as using std::decay (which is equivalent to std::add_pointer for function types): S<std::decay_t<T>> t; Demo
74,082,122
74,082,245
С++ how to make a gif from bmp
I need to implement gif from bmp to animate Abelian sandpile model using only c++ standard library.
Ideally, your starting points would be specifications for GIF and BMP. The GIF Specification, is a pretty easy thing to find. Unfortunately, (at least to the best of my knowledge) Microsoft has never brought all the information about BMP format into a single document to act as a specification. There's a lot of documentation in various places, but no one place that has all of it together and completely organized (at least of which I'm aware). That means you're kind of stuck with a piecemeal approach. Fortunately, you probably don't need to read every possible legitimate BMP file--it's been around a long time, so there are lots of variations, many of which are rarely used any more (e.g., 16-color bitmaps). At a guess, you probably only need to deal with one or two specific variants (e.g., 24 or 32-bits per pixel), which makes life a great deal easier. Here's a page that gives at least a starting point for documentation on how BMP files are formatted. You'll probably need to consider at least a few ancillary problems though. Unless your input BMP files use 8 bits per pixel with a palette to define the color associated with each of those 255 values, you're probably going to have at least one other problem: you'll most likely be starting with a file that has lots of colors (e.g., as noted above, 24 or 32 bits per pixel), but for a GIF file you need to reduce that to only 8 bits per pixel, so you'll need to choose 255 colors that best represent those in the pictures you care about, then for each input pixel, choose one of those 255 colors to represent that pixel as well as possible. Depending on how much you care about color fidelity vs. spatial resolution, there are multitudes of ways of doing this job, varying from fairly simple (but with results that may be rather mediocre) to extremely complex (with results that may be somewhat better, but will probably still be fairly mediocre).
74,082,584
74,082,645
When insert()ing into a std::map why is the copy-contructor called twice?
Why is the copy-constructor called twice in this code? // main.cpp #include <iostream> #include <map> #include <string> using namespace std; class C { private: int i_; char c_; public: C(int i, char c) : i_(i), c_(c) { cout << "ctor" << endl; } C(const C& other) { cout << "copy-ctor" << endl; } }; int main(int argc, char* argv[]) { map<string, C> m; m.insert({"hello", C(42, 'c')}); return 0; } Build & output: $ g++ --version && g++ -g ./main.cpp && ./a.out g++ (Debian 6.3.0-18+deb9u1) 6.3.0 20170516 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. ctor copy-ctor copy-ctor
The map value type is std::pair<const int, C>. C is not movable, thus std::pair<const int, C> is not movable. m.insert({"hello", C(42, 'c')}); Creates C and copies it to a pair, local variable value in insert, then copies a pair to a map bucket. m.emplace("hello", C(42, 'c')); will copy C only once to a bucket. Compiler options... Program returned: 0 Program stdout ctor copy-ctor
74,082,811
74,101,910
What is the best way to store authentication (login) in a system when a user has been authenticated using shadow in Linux with C++
I have a project called kos and it's a simple SUID tool, recently as a lot of people in private have been asking me I added authentication storing/remembering, but it's not that good So what happens basically is: Verify that the user has entered the correct password If the password is correct set the temp_validate_user variable to true and temp_validate_user_id to the authenticated user's ID (e.g. 1000) In the run_command function, after setting the appropriate IDs (uid, euid, gid and egid) do: If the last modified timestamp is less than the set max ammount, remove /var/kos/<user id> Else if temp_validate_user is still set make sure /var/kos exists, if not make it then make a file called /var/kos/<user id> (e.g. /var/kos/1000) To put it simply we just store a file called /var/kos/<user id> and then check if its last modified timestamp is less than the max ammount But we got a problem Even though the dir is root-only with kos you can get root and if you verify once you can do this: while true; do echo | kos touch "/var/kos/$(id -u)"; done And when the user authenticates the file will be be updated all the time meaning you can have infinite root bypass So the question is, is there ANY better way to do this, I really need to find a better way because as more of the time passes I keep getting more and more worried about it and I can't think of anything Oh and if it wasn't clear already, I don't want to use PAM or anything else other than pure C or C++ Related commits and lines of code: https://github.com/TruncatedDinosour/kos/commit/cbcc1346d76b0c47bb4658a1b650de11f74a2727 https://github.com/TruncatedDinosour/kos/blob/main/src/config.h#L62 https://github.com/TruncatedDinosour/kos/blob/main/src/macros.hpp#L40 https://github.com/TruncatedDinosour/kos/blob/main/src/main.cpp#L37 https://github.com/TruncatedDinosour/kos/blob/main/src/main.cpp#L46 https://github.com/TruncatedDinosour/kos/blob/main/src/main.cpp#L23 https://github.com/TruncatedDinosour/kos/blob/main/src/main.cpp#L175 https://github.com/TruncatedDinosour/kos/blob/main/src/main.cpp#L185 https://github.com/TruncatedDinosour/kos/commit/f8c4e79e798c0ffaa15df9d1d77fb91b54e61599 https://github.com/TruncatedDinosour/kos/commit/9ee54bbd01281016d1170c37b0a6cd23433b1227 Thanks for the answers in advance :) Questions and answers What's your goal? Store that the user has logged in for x ammount of seconds then if x seconds have passed invalidate it, but until x seconds hasn't passed don't ask the specific logged in user to enter their password
As @ThomasWeller sudo does the same thing, meaning it's secure enough, I dropped the terms on the dir from 744 to 711 and file perms from 744 to 600 Thank you @ThomasWeller once again
74,082,864
74,083,695
how to insert vector element into link with cURL c_str() function in C++?
I'm working on a c++ code that fetches a variable from a text file and adds it to a fixed url, similarly to the following example: int x = numbers[n]; string url = "http://example.com/" + x; curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); but I'm getting this error message after compiling Protocol "tp" not supported or disabled in libcurl How can I fix that?
You are adding an int to a const char* pointer (that was decayed from a string literal of type const char[20]). That will offset the pointer by however many elements the int indicates. Which, in your case, appears to be 2, which is why CURL thinks the URL begins with tp: instead of http:. Your code is basically the equivalent of this: const char strliteral[] = "http://example.com/"; ... int x = numbers[n]; const char *p = strliteral; string url = p + x; // ie: &p[x] h t t p : / / e x a m p l e . c o m / ^ ^ | | p p+2 To fix that, you can use std::to_string() in C++11 and later to convert the int to a string, eg: string url = "http://example.com/" + to_string(x); Or, you can use a std::ostringstream (in all C++ versions), eg: ostringstream oss; oss << "http://example.com/" << x; string url = oss.str(); Or, you can use std::format() in C++20 and later (you can use the {fmt} library in earlier versions), eg: string url = format("http://example.com/{}", x); // or: string url = format("{}{}", "http://example.com/", x);
74,082,882
74,085,642
Qt C++ - How to pass slider value into function that will be slotted into another slider?
I'm super new to Qt so bear with me. I'm doing my class assignment in which I need to create a window with 3 sliders and a label in which I can load my image. These 3 sliders are corresponding to HSL (Hue, Saturation, Luminance) that of course will change my image. Math needed for these transformations is done. I have problem strictly to Qt, because I've never worked with it previously. Assuming I have function in which I'm doing all transformations: void hsl(const QImage& src, QImage& dst, float delta_h, float delta_s, float delta_l) Then, I have function to apply these transformation to my image: void MainWindow::changeHSL(int h, int s, int l) { hsl(originalImage, processImage, h, s, l); ui->label->setPixmap(QPixmap::fromImage(processImage)); } And then, I need to slot this function to my sliders. And this is where I have problem. MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) , ui(new Ui::MainWindow) { ui->setupUi(this); connect(ui->actionOpen, SIGNAL(triggered(bool)), this, SLOT(openImage(bool))); connect(ui->horizontalSlider, SIGNAL(valueChanged(int)), this, SLOT(changeHSL(int, int, int))); connect(ui->horizontalSlider_2, SIGNAL(valueChanged(int)), this, SLOT(changeHSL(int, int, int))); connect(ui->horizontalSlider_3, SIGNAL(valueChanged(int)), this, SLOT(changeHSL(int, int, int))); } Slotting this function that way is incorrect, I have errors with incompatible sender/receiver arguments. Changing function to have one argument is also prohibited, I need it to have three arguments like how I wrote it. I asked my teacher during class how I should resolve this, but he said that in every sliders somehow I need to pass value from other sliders. Unfortunately, my experience with Qt is none and I simply don't have any idea how to do it. If you're afraid to help me because of "class assignment" don't worry - it is only about math behind image processing. Qt is only a tool chosen by my teacher because most of my colleagues had experience with it. Unfortunately I do not, so I'm trying to catch up real quick. Thanks for all replies.
You can't connect signals and slots like that. Try use my solution: Remove the parameters of MainWindow::changeHSL(int h, int s, int l), replace the h, s, l into the values of h, s, l sliders (They're ui->horizontalSlider, ui->horizontalSlider_2, ui->horizontalSlider_3), like this: void MainWindow::changeHSL() { int h = ui->horizontalSlider->value(); int s = ui->horizontalSlider_2->value(); int l = ui->horizontalSlider_3->value(); hsl(originalImage, processImage, h, s, l); ui->label->setPixmap(QPixmap::fromImage(processImage)); } Rewrite the connections: MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) , ui(new Ui::MainWindow) { ui->setupUi(this); connect(ui->actionOpen, SIGNAL(triggered(bool)), this, SLOT(openImage(bool))); connect(ui->horizontalSlider, &QSlider::valueChanged, this, &MainWindow::changeHSL); connect(ui->horizontalSlider_2, &QSlider::valueChanged, this, &MainWindow::changeHSL); connect(ui->horizontalSlider_3, &QSlider::valueChanged, this, &MainWindow::changeHSL); } Hard to explain why didn't your code go wrong because I had a bad English. But anyway, I hope my code will help you something ;)
74,082,951
74,083,137
How do I translate reinterpret_cast<WPARAM>(reinterpret_cast<LPCREATESTRUCT>(lParam)->hwndParent) to VB6?
I neeed to convert a piece of code from C++ to VB6. Specifically, this one: reinterpret_cast<WPARAM>(reinterpret_cast<LPCREATESTRUCT>(lParam)->hwndParent) Can somebody tell me what this would look like in VB6? I am not experienced enough in C++ to understand what exactely this does. Thank you very much! About the background of this question: A control doesn't seem to have full Unicode support if it is used in Visual Basic 6. Why? The forms, that Visual Basic 6 is creating, are ANSI windows. Therefore they force the control's underlying native treeview window class to use ANSI messages when communicating with the form. This breaks Unicode support in some situations. To work around this problem, the WM_NOTIFYFORMAT message must be reflected back to the control. In Visual Basic, you must subclass the control's container window and send WM_NOTIFYFORMAT back to the window that it was sent for. In C++, message reflection works similar. LRESULT ExplorerTreeView::OnCreate(UINT message, WPARAM wParam, LPARAM lParam, BOOL& /*wasHandled*/) { LRESULT lr = DefWindowProc(message, wParam, lParam); if(*this) { // this will keep the object alive if the client destroys the control window in an event handler AddRef(); /* SysTreeView32 already sent a WM_NOTIFYFORMAT/NF_QUERY message to the parent window, but unfortunately our reflection object did not yet know where to reflect this message to. So we ask SysTreeView32 to send the message again. */ SendMessage(WM_NOTIFYFORMAT, reinterpret_cast<WPARAM>(reinterpret_cast<LPCREATESTRUCT>(lParam)->hwndParent), NF_REQUERY); Raise_RecreatedControlWindow(HandleToLong(static_cast<HWND>(*this))); } return lr; }
That's just the handle of the form where the control resides, you can replace that code with Me.hWnd.
74,083,171
74,083,255
Implicit instantiation of undefined template 'boost::enable_shared_from_this<TCP_Connection>'
I've been trying to follow a Boost tutorial to integrate Asio for a few hours now, but I have a class inheritance problem with Boost's enable_shared_from_this class. I've included everything I needed for this class but the problem still persists and I'm not sure what this message means Implicit instantiation of undefined template 'boost::enable_shared_from_this<TCP_Connection>' #pragma once #include <boost/asio.hpp> #include <boost/array.hpp> #include <boost/bind.hpp> #include <iostream> #include <array> using boost::asio::ip::tcp; class TCP_Connection : public boost::enable_shared_from_this<TCP_Connection> { public: typedef boost::shared_ptr<TCP_Connection> pointer; static pointer create(boost::asio::io_context &ioc); tcp::socket& socket(); void start(); private: explicit TCP_Connection(boost::asio::io_context &ioc); void handleWrite(); tcp::socket _socket; std::string _message; };
#include <boost/enable_shared_from_this.hpp>
74,083,298
74,083,904
How can I access a private (non-static) method in C++?
Currently I am working on a project where I want to control a model train for a nice showcase. I have multiple locomotives which all have a unique address (just think of it as a UUID). Some locomotives have a headlight, some of them have a flashing light, some have both and some of them have none. My base class is this: class GenericLocomotive : public Nameable, public Describable { private: uint16_t address; public: GenericLocomotive(const char* name, const char* description, uint16_t address); void setFunction(uint8_t command, bool val); Now I want to have a different class which provides the functionality to enable and disable the headlight: class HasHeadLight { public: void activateHeadlight(); void deactivateHeadlight(); } My goal is to have a specific class for every locomotive (with different functionality) which looks something like this: class <SpecificLocomotive> : public GenericLocomotive, public HasHeadlight, public HasFlashlight,... { ... } The problem is, that I must have access to the private field 'address' of my GenericLocomotive class and I also have to call the function setFunction(...) from my HasHeadlight class. I am quite new to C++ and just found out about the concept of friend classes and methods, but I can not quite get it to work, because even with the declaration of the method setFunction(...) as a friend, I can not just call something like this->setFunction(HEADLIGHT_COMMAND, true); from my HasHeadlight-class, because the function is not declared in 'this'. How can I access the method from my other class? Is this friend thing even needed or is there a completely different way to structure my C++ program?
You have misunderstood how class inheritance works: Inheritance establishes an is-a relationship between a parent and a child. The is-a relationship is typically stated as as a specialization relationship, i.e., child is-a parent. There are many ways you can tackle what you want to achieve here, but this is not it. You're on the right track as far as treating the different train components as separate objects, and one way to achieve that would be to instead make each component a member of the specialized locomotive: class HeadLight { public: void activateHeadlight(); void deactivateHeadlight(); } class SpecialLocomotive : public GenericLocomotive { HeadLight mHeadlight; Flashlight mFlashlight; public: SpecialLocomotive(const char* name, const char* description, uint16_t address) : GenericLocomotive(name, description, address) { setFunction(HEADLIGHT_COMMAND, true); } void toggleLight(bool on) { if (on) { mHeadlight.activateHeadlight(); } else { mHeadlight.void deactivateHeadlight(); } } /* so on and so forth /* } There's not enough details to go further with it. If you need to call setFunction from within Headlight, I would consider that a poor design choice, but there are other ways.
74,083,370
74,083,417
How template class resolve member methods
I used to do what suggested here https://isocpp.org/wiki/faq/templates#separate-template-fn-defn-from-decl to separate template header and implementations. We basically explicitly instantiate the desired template at the end of .cc file so that the compilation unit contains enough information for the linker to work with. I recently learnt that we only need to explicitly instantiate a class constructor to be able to create an instance. For example, // .h file template<typename T> class A { public: A(T& t) : t_(t) {}; void PublicMethod(); private: void PrivateMethod(); T& t_; }; // .cc file template<typename T> void A<T>::PublicMethod() { PrivateMethod; return;} template<typename T> void A<T>::PrivateMethod() { // Do some work. return; } // Here I only instantiate the constructor and public interface. template A::A(int); template void A<int>::PublicMethod(); // In main, I can do following. int main() { A<int> a(2); a.PublicMethod(); } The part I am not clear is: if I instantiate the public method, does it automatically instantiate all relevant private methods as well automatically?
No, if you explicitly instantiate a member (including a constructor), then only the definition for that member will be explicitly instantiated. The explicit instantiation may cause implicit instantiation of other members of the class, but that isn't enough to use these members in a different translation unit. If you do not intent to use the private members in a different translation unit though, then it would be sufficient to explicitly instantiate the public/protected member functions. If you want to explicitly instantiate all class members, you should explicitly instantiate the class template specialization itself: template class A<int>; template A::A(int); This is not correct. Your constructor expects a reference, so it should be int& instead of int. Furthermore A is the template, not a specialization of it. You must specify a specialization: template A<int>::A(int);
74,083,711
74,091,640
How do I create a timer that I can query during the program and whose format is int, long or double?
I want to start a clock at the beginning of my program and use its elapsed time during the program to do some calculations, so the time should be in a int, long or double format. For example i want to calculate a debounce time but when i try it like this i get errors because the chrono high resolution clock is not in an int, long or double format and therefore i can't subtract 50ms from that (my debounceDelay) or save that value to a double (my lastDebounceTime). Originally i had a working Arduino Game (Pong) with an LCD and i want to convert this into a C++ console application. On the Arduino there was this function "millis()" that gave me the runtime in ms and this worked perfectly fine. I can't find a similar function for C++. double lastDebounceTime = 0; double debounceDelay = 50; void Player1Pos() { if ((std::chrono::high_resolution_clock::now() - lastDebounceTime) > debounceDelay) { if ((GetKeyState('A') & 0x8000) && (Player1Position == 0)) { Player1Position = 1; lastDebounceTime = std::chrono::high_resolution_clock::now(); } else if ((GetKeyState('A') & 0x8000) && (Player1Position == 1)) { Player1Position = 0; lastDebounceTime = std::chrono::high_resolution_clock::now(); } } I am very new to C++ so any help is greatly appreciated. Thank you all!
I find the question misguided in its attempt to force the answer to use "int, long, or double". Those are not appropriate types for the task at hand. For references, see A: Cast chrono::milliseconds to uint64_t? and A: C++ chrono - get duration as float or long long. The question should have asked about obtaining the desired functionality (whatever the code block is supposed to do), rather than asking about a pre-chosen approach to the desired functionality. So that is what I will answer first. Getting the desired result To get the code block to compile, you just have to drop the insistence that the variables be "int, long, or double". Instead, use time-oriented types for time-oriented data. Here are the first two variables in the code block: double lastDebounceTime = 0; double debounceDelay = 50; The first is supposed to represent a point in time, and the second a time duration. The C++ type for representing a point in time is std::chrono::time_point, and the C++ type for a time duration is a std::chrono::duration. Almost. Technically, these are not types, but type templates. To get actual types, some template arguments need to be supplied. Fortunately, we can get the compiler to synthesize the arguments for us. The following code block compiles. You might note that I left out details that I consider irrelevant to the question at hand, hence that I feel should have been left out of the minimal reproducible example. Take this as an example of how to simplify code when asking questions in the future. // Use the <chrono> library when measuring time #include <chrono> // Enable use of the `ms` suffix. using namespace std::chrono_literals; std::chrono::high_resolution_clock::time_point lastDebounceTime; // Alternatively, if the initialization to zero is not crucial: // auto lastDebounceTime = std::chrono::high_resolution_clock::now(); auto debounceDelay = 50ms; void Player1Pos() { if ((std::chrono::high_resolution_clock::now() - lastDebounceTime) > debounceDelay) { // Do stuff lastDebounceTime = std::chrono::high_resolution_clock::now(); } } Subtracting two time_points produces a duration, which can be compared to another duration. The logic works and now is type-safe. Getting the desired approach OK, back to the question that was actually asked. You can convert the value returned by now() to an arithmetic type (integer or floating point) with the following code. You should doubts about using this code after reading the comment that goes with it. // Get the number of [some time units] since [some special time]. std::chrono::high_resolution_clock::now().time_since_epoch().count(); The time units involved are not specified by the standard, but are instead whatever std::chrono::high_resolution_clock::period corresponds to, not necessarily milliseconds. The special time is called the clock's epoch, which could be anything. Fortunately for your use case, the exact epoch does not matter – you just need it to be constant for each run of the program, which it is. However, the unknown units could be a problem, requiring more code to handle correctly. I find the appropriate types easier to use than trying to get this conversion correct. Especially since it required no change to your function.
74,083,798
74,083,833
to check the multiple of five and two
#include using namespace std; int main () { int multiple; cout << "Please give a number you want to check the multiple of: "; cin >> multiple; if ((multiple % 5 == 0), (multiple % 2 == 0)); { cout << multiple << " is multiple of five. " << endl; cout << multiple << " is the multiple of two. "; } else { cout << multiple << " is not multiple of five. " << endl; cout << multiple << " is not the multiple of two. "; } return 0; } I can't find the error in the code. It shows error in the else statement. I can't find the error in the code. It shows error in the else statement. I can't find the error in the code. It shows error in the else statement. I can't find the error in the code. It shows error in the else statement. I can't find the error in the code. It shows error in the else statement. I can't find the error in the code. It shows error in the else statement. I can't find the error in the code. It shows error in the else statement. I can't find the error in the code. It shows error in the else statement.
It shows an error in the else statement because C++ doesn't expect a semi-colon (;) at the end of your if statement. When C++ sees a ; your if-statement is considered done. It has no effect — it just skips it. Also, your if-syntax is wrong. It shouldn't have a comma ,. This should be what you intended to do: if (multiple % 5 == 0 && multiple % 2 == 0) { cout << multiple << " is a multiple of five. " << endl; cout << multiple << " is a multiple of two. "; } else { cout << multiple << " is not a multiple of five. " << endl; cout << multiple << " is not a multiple of two. "; }
74,083,911
74,084,118
private static member in base class being acessed by derived classes
I am currently using the old VC++98, and I am facing issues trying to encapsulate a static member declared as private in a base class. I wish that the derived classes do not have access to such static member, but I can't find out how. The following example code is compiling and running without problems (whereas it should not, in my opinion): class Base { private: static int integer; }; int Base::integer=0; //initialization class Derived : public Base { public: int GetInteger(){return Base::integer;} }; How can I make the static member inacessible in the derived class?
How can I make the static member inaccessible in the derived class? Use a compliant compiler. The code doesn't compile in standard C++ (any version) just like you expect.
74,084,022
74,084,028
C++11 namespace scoping with functions
Right now, I am coding a complex project in c++. I've simplified the example, where in a namespace I'm defining two functions, that both need each other. namespace Example { void foo() { bar(); } void bar() { foo(); } } Is there any way to fix my issue, without separating the functions from the namespace?
You can forward-declare inside a namespace exactly the same way you can do it at global namespace scope: namespace Example { void bar(); void foo() { bar(); } void bar() { foo(); } } However, as for any function, if these are functions defined in a header file shared between multiple translation units, then you would need to mark them inline. If they are functions declared and defined only in one .cpp meaning in one translation unit, then they should probably be marked static, so that other functions with the same name can be declared in other translation units without name clash and consequent ODR violations and UB. Also, you can open and close a namespace as often as you want and in as many files and translation units as you want. E.g. namespace Example { void foo(); void bar(); } in a header file and #include<header.h> namespace Example { void foo() { bar(); } void bar() { foo(); } } in a corresponding .cpp is also fine.
74,084,081
74,084,110
difference between size_t and int in a "Plus One" problem algorithm
vector<int> plusOne(vector<int>& digits) { int n = digits.size(); for (int i = n - 1; i >= 0; i--){ if (digits[i] < 9){ digits[i]++; return digits; } else{ digits[i] = 0; } } digits.insert(digits.begin(), 1); return digits; } it's a Plus One problem. "You are given a large integer represented as an integer array digits, where each digits[i] is the ith digit of the integer. The digits are ordered from most significant to least significant in left-to-right order. The large integer does not contain any leading 0's. Increment the large integer by one and return the resulting array of digits." why this particular solution does not work with size_t instead of int in for loop?
Because size_t is an unsigned type. If i is a size_t, then i >= 0 is always true because, by definition, an unsigned value is never less than 0. To make it work with a size_t type it will be necessary to adjust the overall logic, in order to accommodate it. Something like: for (size_t i = digits.size(); i-- > 0; ){
74,084,223
74,084,224
Difference between lambda and member function pointer
In my answer here, Barry pointed out that it's better to call views::transform(&Planter::getPlants) because views::transform([](Planter const& planter){... accidentally copies. #if 1 auto plants = planters | std::views::transform([](Planter const& planter){ return planter.getPlants();}) | std::views::join | std::views::common ; // Plant copy constructor // Plant copy constructor // Plant copy constructor // Plant copy constructor // Plant copy constructor #else auto plants = planters | std::views::transform(&Planter::getPlants) | std::views::join ; #endif // Plant copy constructor // Plant copy constructor Here Plant is a wrapper around int and Planter is a wrapper around std::vector<int>. https://godbolt.org/z/dr7PM5Tvd
Oh I actually know this one. The deduced return type of the lambda actually decays the const ref qualifiers of getPlants. You can fix this by declaring the return type of the lambda to be decltype(auto) views::transform([](Planter const& planter) -> decltype(auto){...}); https://godbolt.org/z/ocK5PG1z1
74,084,270
74,084,592
Can you achieve fn(x1 ^ fn(x0)) with a fold expression?
Is it possible to achieve the following using a fold expression? template<class... Args> auto foo(Args... args) { //calling foo(x0, x1, x2) should be exactly equivalent to //calling fn(x2 ^ fn(x1 ^ fn(x0))) }
If you insist on a fold expression, something along these lines could probably be made to work (not tested): template <typename T> struct Wrapper { T& val; }; template <typename T, typename U> auto operator^(Wrapper<T> l, Wrapper<U> r) { return Wrapper(r.val ^ fn(l.val)); } template<class... Args> auto foo(Args... args) { return fn((... ^ Wrapper<Args>(args)).val); }
74,084,392
74,097,720
How to declare context type whe using multiple 'with' directives?
I have known that it is possible to get information like position_cache and error_handler at the same time by using multiple with directives refer to this doc: https://www.boost.org/doc/libs/1_75_0/libs/spirit/doc/x3/html/spirit_x3/tutorials/annotation.html It can be configured like this when initializing the parser with<tag1>(data1) [ with<tag2>(data2)[p] ] But I'm still not sure how to manipulate the parser's context configuration when using tag1 and tag2 simultaneously. In the boost-spirit official example. I can only find code that demonstrate how to config context type when using just single with directive. like the code below typedef x3::context< error_handler_tag , std::reference_wrapper<error_handler_type> , phrase_context_type> context_type; So I want to know how to declare this context type for a parser that can with two different tag?
Note how context chains to the underlying context (phrase_context_type). You can rinse-repeat: using iterator_type = std::string::const_iterator; using phrase_context_type = x3::phrase_parse_context<x3::ascii::space_type>::type; using error_handler_type = error_handler<iterator_type>; using error_context_type = x3::context<error_handler_tag, std::reference_wrapper<error_handler_type>, phrase_context_type>; using context_type = x3::context<custom_with_tag, CustomType, error_context_type>;
74,085,227
74,170,250
How to deal with IntelliSense not being able to recognize C++20 features?
It's not new that IntelliSense often lags behind C++ development. For instance, the code below is valid in C++20, using the new Template String-Literal Operator feature. template<typename C, size_t Size> struct StrWrapper { std::array<C, Size> m_buf; consteval StrWrapper(const C(&str)[Size]) : m_buf{} { std::copy(str, str + Size, m_buf.begin()); } }; template <StrWrapper c> consteval auto operator ""_wrap() { return c; } "hello world"_wrap; But IntelliSense will report these errors: E2500 a literal operator template must have a template parameter list equivalent to '<char ...>' E2486 user-defined literal operator not found I have found others who have the same problem, there are two reports on Developer Community, the earliest one is from Jan 2021, it's been nearly two years since. It looks like Microsoft didn't want to solve the issue since this feature is somewhat not used often, and they're still struggling with the modules. Is there any way to work around this? I've searched for a way to disable specific errors in IntelliSense but there seems to be none. Actually, there is one but it wouldn't help in this case since every single string that uses ""_wrap would have to be in the __INTELLISENSE__ preprocessor block.
Depending on how you use the return value of your operator afterwards, you might satisfy IntelliSense by providing a dummy implementation just for IntelliSense: template <typename C, size_t Size> struct StrWrapper { std::array<C, Size> m_buf; consteval StrWrapper(const C (&str)[Size]) : m_buf{} { std::copy(str, str + Size, m_buf.begin()); } }; #ifndef __INTELLISENSE__ template <StrWrapper c> consteval auto operator""_wrap() { return c; } #else // Dummy, only seen by IntelliSense. consteval auto operator""_wrap(const char*, size_t) { return StrWrapper(""); } #endif void foo() { constexpr auto t = "hello world"_wrap; }
74,085,373
74,085,449
The correct syntax of a member which is a class template
I have a class : template<typename F1, typename F2, typename F3> class A { F1 f1; F2 f2; F3 f3; A(F1 f1_, F2 f2_, F3 f3_) : f1{f1_}, f2{f2_}, f3{f3_} {}; apply_f1() {f1();}; apply_f2() {f2();}; apply_f3() {f3();}; } and have the following class where I need to instantiate class A with certain lambda functions. My lambda functions require that I capture this since I need certain class members within the lambda. The required interface of the lambdas: [this](void)->void class B { A a // How to instantiate it correctly. // .. other stuff. } Since I dont know how to instantiate A within class B as a member, So far what I have done is creating a static instance of class A within the constructor of class B like this: B::B(){ auto f1 = [this]() {....}; auto f2 = [this]() {....}; auto f3 = [this]() {....}; static A a = A(f1,f2,f3); SomeEventRegisterClass(a); } The SomeEventRegisterClass will essentially register the instance of class A and for now let us just assume that it knows which of the lambdas (apply_f1, apply_f2, apply_f3) to invoke on certain events. In the example above I must declare the variable a static because otherwise if just declared locally it will go out of scope right after the constructor has finished. Therefore, when a particular event triggers and SomeEventRegisterClass attempts to use the instance of class A its lambda's will have been gone out of scope. The fix with using static above is giving other problems; a simple one when used in the GTEST framework and you are running several tests in one executable, the static will only be defined once. Therefore, I am trying to see if it is possible to create such instance per class and where the lambdas will have same scope as class B
You could declare a as A<std::function<void()>, std::function<void()>, std::function<void()>>. That will let it accept capturing lambdas: #include <functional> class B { public: B() : a([this] {}, [this] {}, [this] {}) {} private: A<std::function<void()>, std::function<void()>, std::function<void()>> a; }; Note that the A constructor must be made public too.
74,085,474
74,085,606
How to transform an adjacency matrix into an incidence Matrix
I'm trying to transform the adjacency matrix into an incidence matrix of an undirected graph. For edges : (1, 2), (1,5), (1,6), (2,3), (2,5), (3,4), (3,5), (4,5), (5,6) Adj matrix is : 0 1 0 0 1 1 1 0 1 0 1 0 0 1 0 1 1 0 0 0 1 0 1 0 1 1 1 1 0 1 1 0 0 0 1 0 and I expect the result for the incidence matrix to be 0 1 0 0 1 1 0 0 0 1 0 1 0 1 0 0 0 0 0 1 0 1 1 0 0 0 0 0 0 1 0 1 0 0 0 0 1 1 1 1 0 1 0 0 0 1 0 0 0 1 0 0 0 0 but, my program returns this : 1 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 1 0 1 1 0 0 0 0 0 0 0 1 0 1 0 0 0 1 0 1 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 My source code : graph constructor Graph(int vertices, int edges) { this->vertices = vertices; this->edges = edges; edge = std::vector<Graph::Edge*>(edges); for (int i = 0; i < edges; i++) { edge[i] = new Edge(this); } } Graph* g = new Graph(numberOfVertices, numberOfEdges); g->edge[0]->src = 1; g->edge[0]->dest = 2; g->edge[1]->src = 1; g->edge[1]->dest = 5; g->edge[2]->src = 1; g->edge[2]->dest = 6; g->edge[3]->src = 2; g->edge[3]->dest = 3; g->edge[4]->src = 2; g->edge[4]->dest = 5; g->edge[5]->src = 3; g->edge[5]->dest = 4; g->edge[6]->src = 3; g->edge[6]->dest = 5; g->edge[7]->src = 4; g->edge[7]->dest = 5; g->edge[8]->src = 5; g->edge[8]->dest = 6; for (i = 0; i < numberOfEdges; i++) { adjacency_matrix[g->edge[i]->src][g->edge[i]->dest] = 1; adjacency_matrix[g->edge[i]->dest][g->edge[i]->src] = 1; } std::cout << "Adjacency matrix : " << std::endl; for (i = 1; i <= numberOfVertices; i++) { for (j = 1; j <= numberOfVertices; j++) { std::cout<<adjacency_matrix[i][j]<<" "; } std::cout << std::endl; } // Incidence Matrix int counter = 0; for( int i = 1; i <= numberOfEdges; i++){ for(int j = i + 1; j < numberOfVertices; j++ ){ if(adjacency_matrix[i][j] == 1){ incidence_matrix[i][counter] = 1; incidence_matrix[j][counter] = 1; ++counter; } } } for( int i = 1; i <= numberOfVertices; i++){ for(int j = 1; j <= numberOfEdges; j++){ std::cout<<incidence_matrix[i][j]<<" "; } std::cout<<std::endl; }
The ideas in the code are correct. But the indexing in the array is wrong. Indexing should start at 0. Note: this also applies when setting up the adjacency matrix. The numbers you use to name the vertices/nodes where originally 1,2,3,4,5,6. I propose to call them 0,1,2,3,4,5. Your original edge (1,2) then becomes (0,1). But if we consistently rename all the vertices everywhere we end up with the same graph. The advantage of this new naming convention is that we can use these names directly as indices in the C++ data structures you are using. (Provided we use the corresponding integer value and not consider these names to be strings.) The specification of the Graph becomes Graph* g = new Graph(numberOfVertices, numberOfEdges); g->edge[0]->src = 0; g->edge[0]->dest = 1; g->edge[1]->src = 0; g->edge[1]->dest = 4; g->edge[2]->src = 0; g->edge[2]->dest = 5; g->edge[3]->src = 1; g->edge[3]->dest = 2; g->edge[4]->src = 1; g->edge[4]->dest = 4; g->edge[5]->src = 2; g->edge[5]->dest = 3; g->edge[6]->src = 2; g->edge[6]->dest = 4; g->edge[7]->src = 3; g->edge[7]->dest = 4; g->edge[8]->src = 4; g->edge[8]->dest = 5; So printing the adjacency matrix becomes: std::cout << "Adjacency matrix : " << std::endl; for (i = 0; i < numberOfVertices; i++) { for (j = 0; j < numberOfVertices; j++) { std::cout<<adjacency_matrix[i][j]<<" "; } std::cout << std::endl; } and the calculation of the incidence matrix becomes: // Incidence Matrix int counter = 0; for( int i = 0; i < numberOfVertices; i++){ //numberOfVertices!! for(int j = i + 1; j < numberOfVertices; j++ ){ if(adjacency_matrix[i][j] == 1){ incidence_matrix[i][counter] = 1; incidence_matrix[j][counter] = 1; ++counter; } } } for( int i = 0; i < numberOfVertices; i++){ for(int j = 0; j < numberOfEdges; j++){ std::cout<<incidence_matrix[i][j]<<" "; } std::cout<<std::endl; } Note that the order of the edges is determined now by the order in which you traverse the adjacency matrix.
74,085,748
74,087,387
Registering callbacks in Lua
I have the following structure (more general criticism on architecture welcome): I have a rather large C++ program doing zillion things. To provide scripting a large number of lowish level commands are handled by Lua. Each "command" has an associated Lua fragment that's called when "command"must be executed. Lua fragments may callback (very low level) C++ functions, but I don't it matters. Lua fragment exits as soon as "command" is initiated. "command" is actually performed outside from both Lua and C++ (think something like starting video play back or recording: Command may be "start", "stop", "rewind", ... but it is not actually carried out from program). In order to know if "command" terminated and, eventually, get exit status I need to actively poll command (I have no callbacks, join or similar functions). Now the real question: I should, in certain instances, known to Lua fragments, schedule some timed call of specific Lua function; this may be one-shot (to handle timeouts) or cyclic (to handle polling). I can easily provide a C++ function starting a thread to handle needs, but I don't know how how to provide C++ with the information about which Lua function will have to be called and how to use it. My current Lua class (no timed callbacks yet) looks like: static inline bool is_whitespace(const std::string& s) { return std::all_of(s.begin(), s.end(), isspace); } class Lua { lua_State *state; std::map<std::string, int> fragments; void push(std::string const& str) { lua_pushstring(state, str.c_str()); } void push(char const* str) { lua_pushstring(state, str); } void push(bool value) { lua_pushboolean(state, value); } void push(uint32_t value) { lua_pushinteger(state, value); } void push(int value) { lua_pushinteger(state, value); } void push(double value) { lua_pushnumber(state, value); } public: void push(std::nullptr_t) = delete; Lua() : state(luaL_newstate()) { luaL_openlibs(state); } void register_c_func(const char *name, lua_CFunction func) { lua_register(state, name, func); } bool is_snippet(const std::string &name) { return fragments.count(name); } int register_snippet(const char *name, const char *fragment) { if (is_snippet(name)) { SPDLOG_ERROR("lua::register_snippet({}): ERROR name already present", name); return LUA_NOREF; } if (!is_whitespace(fragment)) { auto ret = luaL_loadstring(state, fragment); if (ret != LUA_OK) { SPDLOG_ERROR("lua::register_snippet({}): Lua registration failed ({})", name, ret); } else { auto r = luaL_ref(state, LUA_REGISTRYINDEX); SPDLOG_TRACE("lua::register_snippet({}, {}): {}", name, fragment, r); fragments[name] = r; return r; } } else { SPDLOG_WARN("lua::register_snippet({}): has empty Lua fragment", name); } return LUA_NOREF; } template<typename... Args> bool exec(const std::string &name, Args... args){ if (is_snippet(name)) { lua_rawgeti(state, LUA_REGISTRYINDEX, fragments.at(name)); ((push(std::forward<Args>(args))), ...); int nargs = sizeof ...(Args); SPDLOG_TRACE("lua::exec({}, {}): {}", name, fragments.at(name), nargs); lua_pcall(state, nargs, LUA_MULTRET, 0); return true; } else { SPDLOG_WARN("lua::exec({}): has no Lua fragment", name); return false; } } void exec(const char* fragment) { SPDLOG_TRACE("lua::exec(): '{}'", fragment); auto ret = luaL_dostring(state, fragment); if (ret) SPDLOG_ERROR("lua::exec(): ERROR {}", ret); } }; extern Lua master_lua; Lua initialization, C++ function registering and snippet registering is outside this scope.
The C function just need to be in the following form. static int registerCallback(lua_State* L) { const char* callbackName = luaL_checkstring(L, 1); //make a copy if you want to save it out of the scope return 0; } lua_register(L, "registerCallback", registerCallback); Then in lua you can pass the name to it. registerCallback("my_callback_function_name")
74,086,666
74,087,067
Is this the correct way of implementing the Consumer Producer problem with multiple Producers?
I'm new to multi-threading programming and I was wondering if there are some best practices when trying to implement the Consumer Producer problem with multiple Producers. This is my current implementation and it seems to work fine, my main doubt is regarding the use of mtx.lock() (for example if I should use a lock_guard instead, and in case what are the advantages for that). Moreover, is it ok to put g_mtx.unlock() right before g_cv.notify_one();? I don't really understand who acquires the mutex and when; my understanding is that the consumer acquires g_mtx right before the g_cv.wait and then releases it when the conditional_variable condition is checked (and is false), then when it gets notified it recheck the variable and if it is true it reacquires the mutex. Is it right? #include <iostream> #include <thread> #include <vector> #include <chrono> std::atomic<int> g_n = 0; static std::condition_variable g_cv; static std::mutex g_mtx; static bool g_notified=false; void consumerFunction(){ while(g_n==0); while(g_n>0){ std::unique_lock<std::mutex> g_lock(g_mtx); std::cout << "[CONSUMER] Waiting for notification..." << std::endl; g_cv.wait(g_lock, []{ std::cout << "[CONSUMER] Notification received!" << std::endl; return g_notified; }); g_n-=1; std::cout << "[CONSUMER] One less Producer!" << std::endl; g_notified = false; } std::cout << "[CONSUMER] CONSUMER FUNCTION HAS COMPLETED ITS WORK" << std::endl; } void producerFunction(){ uint32_t count; for(uint32_t i = 0; i < 10; i++){ // Count until 10... std::this_thread::sleep_for(std::chrono::seconds(1)); } g_mtx.lock(); g_notified=true; g_mtx.unlock(); std::cout << "[PRODUCER] Notifying..." << std::endl; g_cv.notify_one(); } int main(){ std::thread consumer([]{consumerFunction();}); g_n=4; std::vector<std::thread> threads; for(int i = 0; i <g_n; i++){ std::this_thread::sleep_for(std::chrono::seconds(5)); threads.emplace_back([]{producerFunction();}); } consumer.join(); for(auto& t: threads){ if(t.joinable()){ t.join(); } } return 0; } Note: If you try to compile this code in your environment you should build it in Debug mode to avoid any optimization (not sure if that's the case but in happened to me before when defining dummy producer functions). Thanks
Overall, this looks fine to me. The spin wait while(g_n==0); is a bit expensive but I guess this is pat of the example and this part will not be used in production. Otherwise, it is better to replace it with a passive waiting approach (typically another wait condition or a semaphore). for example if I should use a lock_guard instead, and in case what are the advantages for that It can be a bit shorter and possibly a bit safer to use it but it does not have a significant impact here on this specific code. Guards are good to ensure the lock is release even in complex/unexpected cases like when an exception occurs (so not much here). Whether you should use it is matter of opinion. is it ok to put g_mtx.unlock() right before g_cv.notify_one(); With the current code, g_cv.wait can spuriously wake up and check for the condition just after g_mtx.unlock() is called and before the g_cv.notify_one(). If so, the checking lambda is called and it will return true, the print can be made visible, the lock can then be released and taken again before calling g_cv.wait which will release the lock just before entering in sleeping mode. All of that before g_cv.notify_one() is called! That being said, the call to g_cv.notify_one() will not be able to fully wake up the new call to g_cv.wait. Indeed, the notification will wake up the wait like a spurious wake up but the g_notified value will be false so the waiting function will not be completed. Thus, this is fine. If you put the notification before the unlock, then the waiting function cannot be completely awaken because the lock needs to be acquired before the check lambda is called. On some platforms, it can cause the waiting thread to wake up due to the notification and then immediately wait for the mutex to be acquired resulting in unnecessary context switches. To quote the C++ documentation: The notifying thread does not need to hold the lock on the same mutex as the one held by the waiting thread(s); in fact doing so is a pessimization, since the notified thread would immediately block again, waiting for the notifying thread to release the lock. However, some implementations (in particular many implementations of pthreads) recognize this situation and avoid this "hurry up and wait" scenario by transferring the waiting thread from the condition variable's queue directly to the queue of the mutex within the notify call, without waking it up. my understanding is that the consumer acquires g_mtx right before the g_cv.wait and then releases it when the conditional_variable condition is checked (and is false), then when it gets notified it recheck the variable and if it is true it reacquires the mutex. Is it right? Yes. g_cv.wait release atomically g_mtx and put the thread in sleep. However, AFAIK, the mutex is acquired before the checking lambda is called. This is important since g_notified is protected by the lock and must be accessed in a locked section. More specifically, the mutex ensure read to g_notified are correct due to the implicit memory barrier generated by acquiring/releasing the mutex. The mutex is released if the checking lambda return false. If so, the thread is put in sleep. In the end, all accesses to g_notified are protected in the code (except the initialization that do not need to be protected).
74,086,758
74,086,778
What purpose does the dot( . ) fulfil in this piece of code
In an example that's in my C++ book, I've found this piece of code at the end of an example problem, which verified if 3 integers were in an arithmetic progression. if (b==(a+c)/2.) I don't think I've seen the dot after 2 ever used in such a way and I don't know what it's purpose is here.
2. is a double literal. It's the same as 2.0. Integer division is different than floating point division, so in some cases having a double instead of an int makes an important difference. Although this form is perfectly valid, for readability purposes often 2.0 is preferred. In some (not all) newer languages derived from C++ like C# it is not allowed, i.e. you are forced to write 2.0.
74,087,025
74,087,876
Generate explicit instantiations with multiple parameters with preprocessor
In my project, I want to have a bunch of explicit instantiations of my templated functions to reduce build time. Now I have a lot of functions, which can have different templates. For this reason (and in case I want to have more of them) I do not want to type them manually, but have them generated by the preprocessor. An example of what I want to have generated: template bool match_any<x>(); template bool match_any<y<x>>(); template bool match_expr<x,y,z>(); whereas x is an integer between 1 and a defined max_dim, y can be one of three values: real, bool, index and z is either 0 or 1. I want to generate now any possible combination of those three functions with the parameters (e.g. template bool match_any<0>(); template bool match_any<1>(); template bool match_any<2>(); ...), but not only specifically those, since I have ~100 of those functions with a similar structure. Through Using macros to define forward declarations I have figured out how to do a repetitive pattern: #define REP_INT_1(f) f(1) #define REP_INT_2(f) REP_INT_1(f) f(2) #define REP_INT_3(f) REP_INT_2(f) f(3) #define REP_INT_4(f) REP_INT_3(f) f(4) #define REP_INT(n,gen) REP_INT_(n,gen) #define REP_INT_(n,gen) REP_INT_##n(gen) which I can then use like #define GEN(x) template bool match_any<x>(); REP_INT(3, GEN) #undef GEN Of course it is simple to repeat this pattern e.g. for strings. But my problem is now, that because of the nature of the pattern (as I pass GEN as a 'function') I cannot of two arguments for GEN. Sure, I can altered the repetition pattern so it works also for two arguments, but then I would have to make a new pattern like this for any number of arguments and also for every order of them, which ultimatly kind of defeats the purpose, because I will have a big block for every function - then I can just write it manually. Does anyone have an idea of to accomplish this with either a different way to 'loop' the possible arguments or how to extend my existing methods so it works for multiple arguments?
You can add to your macros like so to achieve a somewhat maintainable list: #define GEN_X(f) REP_INT(3, f) #define GEN_Y(f, x) f(x, real) f(x, bool) f(x, index) #define GEN_Z(f, x, y) f(x, y, 0) f(x, y, 1) // GEN_F3 = generate functions with at least 3 arguments #define GEN_F3(x, y, z) template bool match_any<x, y, z>(); #define GEN_F2(x, y) template bool match_any<y<x>>(); GEN_Z(GEN_F3, x, y) #define GEN_F1(x) template bool match_any<x>(); GEN_Y(GEN_F2, x) GEN_X(GEN_F1) demo We separate our variable generators which we can then chain together to get all our permutations: Your macro generates the x's, which is piped into GEN_F1, which handles the single-argument case and pipes those x values to the y-generator, and so on. Be careful that although we've made the source code linearly maintainable, we can't avoid the exponential increase to the executable size. To address your extended question, if you wanted to be able to handle any permutation of numbers for two arguments, say for x={1,2,3}, y={1,2,3,4}, intuitively you may want to adjust like so: #define GEN_X(f) REP_INT(3, f) #define GEN_Y(f, x) REP_INT(4, f) This almost works, but macro expansion prevents using the same REP_INT_* macros again within the one recursive expansion (at least in the way that I've done it). One work-around is to have two REP_INT lists (and at least one of them needs to handle variadic inputs, appending the number to the end). The macros can be identical, except that the names need to differ to allow the expansion to continue. We can then solve the extended problem like so: #define GEN_X(f) REP1_INT_3(f) #define GEN_Y(f, x) REP2_INT_4(f, x) #define GEN_F2(x, y) template bool match_any<x, y>(); #define GEN_F1(x) GEN_Y(GEN_F2, x) GEN_X(GEN_F1) demo
74,087,188
74,087,263
Why this constexpr expression gives me an error?
In the code below, constexpr for the line 2 does not give an error, but line 1 does. #include <iostream> using namespace std; class ComplexNum{ public:constexpr ComplexNum(int _r=0,int _i=0):r(_r),i(_i){} private: int r,i; }; int randGen(){ return 10; } constexpr int numGen(int i,int j){ return i+j; } int main() { constexpr int i=10,j=20; constexpr ComplexNum c3(randGen(),randGen()); //line 1 constexpr ComplexNum c4(numGen(i,j),numGen(i,j));//line 2 return 0; } From the knowledge I have, constexpr evaluates the expression at compile time. Then, shouldn't the compiler be able to evaluate the expression in line 1, because it returns a constant integer (10 in this case)?. If not, how will line 2 be okay?
The compiler can't compile line one because randGen() is not constexpr. The compiler can't magically tell if a function is constexpr. Maybe it looks constexpr, but you actually want it to run at runtime. For that reason, the compiler doesn't evaluate expressions which are not marked constexpr explicitly. Do this: #include <iostream> using namespace std; class ComplexNum{ public:constexpr ComplexNum(int _r=0,int _i=0):r(_r),i(_i){} private: int r,i; }; constexpr int randGen(){ return 10; } constexpr int numGen(int i,int j){ return i+j; } int main() { constexpr int i=10,j=20; constexpr ComplexNum c3(randGen(),randGen()); //line 1 constexpr ComplexNum c4(numGen(i,j),numGen(i,j));//line 2 return 0; }
74,087,799
74,087,860
I read the input number with getchar(), why is the number reversed in the linked list?
I typed 1234, but the list has 4,3,2,1 in it. I suspect the problem is getchar() itself, or a function in the class, but I have no way to find out. The link class is responsible for some linked list operations, such as deletion, insertion, etc., while the node class is responsible for creating and assigning nodes. The createlist class is responsible for the creation of the linked list, which is the main source of the problem. I wrote the debug statement in it, so you can run it and see the results for yourself using namespace std; class Node { public: int data; Node *next; Node() { next = nullptr; } Node(int data) { this->data = data; } Node(const Node &temp) { this->data = temp.data; } }; class Link { public: Node *head; int length = 0; Link() { head = new Node(); } ~Link() { while (head != nullptr) { Node *p = head->next; free(head); head = p; } } void insert(const Node &cache) { Node *temp = new Node(cache); temp->next = head->next; head->next = temp; length++; } }; void Creatlist(Link &link) { char cache; while (1) { cache = getchar(); if (cache == '\n') break; link.insert(Node(cache - '0')); cout << cache << " "; } cout<<endl; Node *p = link.head->next; cout << "in the linklist:"; while (p != nullptr) { cout << p->data << " "; p = p->next; } } int main() { Link link; cout<<"inut numbers:"<<endl; Creatlist(link); }```
With the insert you inserted to the FRONT of the list. So you had "1", then "2->1" ... If you want to insert to the end, don't insert at the head, but hake a Node* tail in the class Link and an insert_end function as //... Node* temp; void insert_end(const Node &cache){ Node *temp = new Node(cache); tail->next=temp; tail=tail->next; length++; } Alsoin the constructor set tail=head
74,088,267
74,088,346
C++ Custom iterator for circular buffer, how to implement end()?
I have written a circular buffer of size N. I've also written a custom iterator. I'm using them for logic like this: auto iter = circular_buffer.begin(); while(iter != circular_buffer.end()) { ++iter; } What is the implementation for end()? Usually it should point to the last element + 1, but if the buffer contains N items, last element + 1 will be the first element and the above code won't even loop once. I cannot do: do { ++iter; } while(iter != circular_buffer.end()); because if the buffer is empty, it will execute once. Is there a way to solve this?
Note: the following assumes that the circular nature of the buffer is a property that is being exposed to the user for their use, rather than being an implementation detail of the system (as is the case for std::list implementations). Giving a circle a proper "range" is something of a problem since... it's a circle. It conceptually has neither a beginning nor an end. One way to do this is to make the "circle" into a helix. Every iterator stores both whatever normal information it needs as well as a cycle count. When an iterator is incremented to whatever the arbitrary "beginning" of the list is, the cycle count is incremented. If the iterator is decremented to before the beginning of the list, the cycle count is decremented. Two iterators are only equal if their position and cycle counts are equal. Most iterators created by the circular list should have a cycle count of zero on construction. The end iterator should have a cycle count of 1 while having the same position in the circle as the begin iterator. Of course, there are some implementation problems. Doing this requires that every iterator's increment/decrement operations to know where the "beginning" of the circle is. So they all need a pointer to the first element or something. But if they have that, then these iterators all become invalid if you modify the list, since that can change what the "first element" is. Now, invalidating iterators on container modification is something that is true of many container iterator types, so it's not too big of a problem. But it is something you should be aware of. That's kind of an unavoidable downside of trying to use ranges with a concept that inherently has neither a beginning nor an end.
74,088,322
74,103,811
Are IUnknown AddRef and Release thread safe?
Are IUnknown AddRef and Release interfaces are thread safe (atomic)? I know what they do are incrementing/decrementing reference counts, but I wonder how they do. Particularly, IUnknown interface that inherits to Direct 3D components such as ID3D12DeviceChild. Version of Direct 3D is 12 if necessary. The reason why I'm mentioning Direct 3D is I've read a statement "DirectX APIs are not "true COM"". So it might differ from "true COM". The reason why I got confused is due to failure in finding official document or proof that the interfaces are internally using whether Interlocked API or using simple increment/decrement operator. Reference of simple increment/decrement operator implementation. ULONG CMyObj::Release() { if (--m_dwRef == 0) { delete this; return 0; } return m_dwRef; } References of Interlocked API (1), (2). ULONG CMyMAPIObject::Release() { // Decrement the object's internal counter. ULONG ulRefCount = InterlockedDecrement(m_cRef); if (0 == m_cRef) { delete this; } return ulRefCount; } Other related references : Programming DirectX with COM How IUnknown Works It is invalid to use an immediate context concurrently with most of the DXGI interface functions. For the March 2009 and later DirectX SDKs, the only DXGI functions that are safe are AddRef, Release, and QueryInterface. I need to know whether they are thread safe because my project is multithreaded so that how I should treat them. If anyone can help, it will be really appreciated.
TL;DR: For Direct3D 11, Direct3D 12, and DXGI, all use of the IUnknown methods should be 'thread-safe'. For Direct3D 11, the methods of ID3D11Device are all 'thread-safe' by design. The methods of ID3D11DeviceContext are not 'thread-safe'. That said, you can safely call AddRef and Release on all ID3D11DeviceChild-derived classes from any thread. For Direct3D 12, the methods of ID3D12Device are also 'thread-safe'. Individual command-lists are not 'thread-safe' so you are expected to only use a command list interface from one thread at time. Keep in mind that in Direct3D 12, the application is responsible for handling all the CPU/GPU synchronization as well. A key difference with Direct3D Device Child objects is that they are NOT immediately cleaned up when their reference counts hit 0. Since it uses 'deferred destruction' they get cleaned up at some later point, typically a Flush or Present.
74,088,402
74,088,602
Overload the ""_something operator on identifiers
Is possible, in C++, to overload the ""_something operator for function identifiers or callables in order to make it have custom behaviour? I recently saw something similar in this cppcon video, where the presenter is exposing how to build a unit test framework using modules, zero macros... but I am not understanding well how the ""_test is possible, or how C++ understands that for that callable should perform such an action defined in the body of the operator overloading implementation. template <typename T> auto "some_name"_test(T a, T b); Can someone explain the details behind this?
The UDL operator "" is just a function call. Functions can return anything. They can, for example, return an object type which has an overloaded operator(), and is therefore callable. They can return an object type with an overloaded operator=, and is therefore assignable. Etc. It's not about how you overload the UDL operator; it's about what your overload returns.
74,089,280
74,089,598
value return by cstyle cast of a variable is prvalue or lvalue?
AFAIK, if you cast to non-reference type, you get an prvalue. int x = 234; (int)x = 23; std::cout << x << "\n"; Output : 23 (in msvc) In GCC and Clang, cstyle cast return a prvalue (as expected), meanwhile in MSVC, it return an lvalue. Am i missing something or it is an bug in MSVC ? see live demo here
If you cast to an lvalue reference type you will get a lvalue. If you cast to rvalue reference type you will get a xvalue. If you cast to non-reference type you get an prvalue. So, you should get a prvalue here. Use the latest version of c++ in msvc, you will get your expected output. Use flag : /std:c++latest
74,089,461
74,089,470
Pointer as an argument in function pointer
Ok so I have a question. How to make a pointer as a argument inside a function pointer? I tried this: void (*myFunction)(*myClass); or void (*myFunction)((*myClass)); But first return error: excepted identifier before * token and second one same but with '('. Any help appreciated. Edit: its inside class definition (.h file).
Try this instead: void (*myFunction)(myClass*); When declaring a pointer for a variable or function parameter, you need to specify the type before the *, and the name after (in a function parameter, the name is optional). So, a pointer to a type named myClass would be declared as myClass* rather than *myClass. The reason the * appears before myFunction rather than after is because myFunction is a name not a type. You are declaring a variable named myFunction whose type is void (*)(myClass*), ie a pointer to a function that returns nothing and takes in a myClass* pointer as a parameter.
74,089,609
74,089,878
How to reuse an IMFSample without consuming additional memory
I wrote a screen video capture program in C++ /CLI. I capture the video 30 times a second and display it in a picture box. My idea was to copy the IMFSample to a reusable output sample then free the source sample to control memory usage. Although I call sampleOut->RemoveAllBuffers() prior to sampleOut->AddBuffer(destBuf), it still consumes additional memory. It appears that RemoveAllBuffers doesn't actually free the memory from the prior video frame. Any idea how I can free the memory without having to release the sampleOut and recreate it? HRESULT ScreenCapture::DuplicateSample(IMFSample* sample) { HRESULT hr = S_OK; if (!sample) { hr = E_ABORT; return hr; } DWORD sampleFlags = 0; LONGLONG llVideoTimeStamp = 0; LONGLONG llSampleDuration = 0; IMFMediaBuffer* srcBuf; IMFMediaBuffer* destBuf; hr = sample->GetSampleFlags(&sampleFlags); hr = sample->GetSampleTime(&llVideoTimeStamp); hr = sample->GetSampleDuration(&llSampleDuration); hr = sampleOut->SetSampleFlags(sampleFlags); hr = sampleOut->SetSampleTime(llVideoTimeStamp); hr = sampleOut->SetSampleDuration(llSampleDuration); srcBuf = nullptr; hr = sample->GetBufferByIndex(0, &srcBuf); byte* srcByteBuffer = nullptr; DWORD srcBuffCurrLen = 0; DWORD srcBuffMaxLen = 0; hr = srcBuf->Lock(&srcByteBuffer, &srcBuffMaxLen, &srcBuffCurrLen); destBuf = nullptr; hr = MFCreateMemoryBuffer(srcBuffCurrLen, &destBuf); byte* destByteBuffer = nullptr; hr = destBuf->Lock(&destByteBuffer, nullptr, nullptr); memcpy(destByteBuffer, srcByteBuffer, srcBuffCurrLen); hr = destBuf->Unlock(); hr = srcBuf->Unlock(); hr = destBuf->SetCurrentLength(srcBuffCurrLen); SafeRelease(&srcBuf); sampleOut->RemoveAllBuffers(); hr = sampleOut->AddBuffer(destBuf); //Memory issue here SafeRelease(&destBuf); return hr; } As you can see I also need a better way to handle the hr testing for each step. I figured I deal with that after I get the code working. Thanks for your help!
The question you are interested in is how to reuse samples instead of allocating them each time. The primary call you want to avoid is MFCreateMemoryBuffer because it is the actual memory consumer, not the buffer attachment/detachment from sample objects. The ideal solution is along these lines: you create a memory allocator (conceptually similar to created by MFCreateVideoSampleAllocatorEx, just your own implementation) the allocator manages a pool of samples, either pre-created or extended on demand your code obtains a sample with respective buffer from memory allocator and before the same is fully released, which you track by looking at COM reference count of the object that implements IMFSample, it is considered as engaged and is not available for reuse from the pool once everyone releases a sample, it returns to the pool and is available for reuse; that is, your video frame processing code will not allocate any new buffers, it will pick next free buffer which is already allocated and available This is exactly how allocators provided by mentioned MFCreateVideoSampleAllocatorEx work.
74,089,619
74,089,817
Proportional scaling a window in Qt
How can I lock the aspect-ratio for resizing the window of my application? For Example aspect-ratio: 16/9.
If you mean you want to be prevent the user from resizing the away from a fixed 16:9 ratio (so e.g. if the user drags the window shorter, it would automatically become thinner as well), I'm not sure that's possible via the Qt API, because window-resizing is handled by the OS's window manager, not by the Qt library itself. Qt only gets notified after the resize-step has already happened. There might be some lower-level API that would constrain the window's aspect ratio to be constant, but that would be OS-specific, not part of Qt. One work-around would be to make the window fixed-size (by calling QWidget::setFixedSize()) so that the user can't resize it by dragging on the edges or corners, and then provide some other resizing mechanism (e.g. "larger" and "smaller" buttons) that the user could activate to resize the window. Another possible work-around that you could do at the Qt level is to react to a resizeEvent() by calculating the largest 16:9 sub-rectangle that will fit inside the new window-size, and layout your content to fit inside that rectangle instead of filling the entire window. That would result in bars of empty space at the top and bottom (or left and right) edges of your window whenever the window wasn't at a 16:9 aspect ratio, but at least your content could still have the desired aspect ratio regardless of how the user resizes the window.
74,089,679
74,089,746
Trouble passing a function pointer to a method from main in C++
I have the following set up: poster.h template<class T> class Poster { private: unique_ptr<Poster<T>> testPtr = nullptr; public: void post(void (*callback_function)(T), T data) { post2(testPtr, callback_function, data); } void post2(unique_ptr<Poster<T>> p, void (*callback_function)(T), T data) { callback_function(data); } }; ... Then in main.cpp i have the following void output(int x) { std::cout << x; } int main() { Poster<int> p; int x = 5; p.post(output, x); } Every time i try to build this i get: Severity Code Description Project File Line Suppression State Error C2280 'std::unique_ptr<Poster<int>,std::default_delete<Poster<int>>>::unique_ptr(const std::unique_ptr<Poster<int>,std::default_delete<Poster<int>>> &)': attempting to reference a deleted function I am not sure why this is. Any help would be greatly appreciated.
In post2(), you take unique_ptr<Poster<T>> by value. That only works if you pass it an rvalue reference ('temporary', or something in std::move()). From your example it's not apparent if you really need unique ownership inside post2() (not generally, but in the function). If you don't need ownership, you might take unique_ptr<Poster<T>>& p, or even simply just Poster<T>& p. If you want ownership to be transferred, and thus testPtr to be emptied, you can write in post(): post2(std::move(testPtr2), ...);
74,089,773
74,089,822
How can I give a global callback function a local instance?
In global namespace I have a GLFW callback function: void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods) { if (key == GLFW_MOUSE_BUTTON_RIGHT && action == GLFW_PRESS) { } } This function must recieve an object from local namespace of main function: int main() { ... Sphere lightSphere{ 0.8f, outerColor, centerColor }; ... } And in main loop I have a GLFW callback function. glfwSetKeyCallback(window, key_callback); Is it possible to implement it without declaring an object in global namespace?
Set the user pointer to window and retrieve it in the callback. glfwSetWindowUserPointer(window, &lightSphere); glfwSetKeyCallback(window, key_callback); void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods) { Sphere* sphere = static_cast<Sphere*>(glfwGetWindowUserPointer(window)); }
74,090,088
74,090,209
Different results of constexpr function during runtime vs compile time
I have this code below that recursively traverses the nodes of a graph (for simplicity, only the edges are shown here). I would expect the result of the count_dfs() function to be 4 regardless of whether the function is evaluated at runtime or compile time. On MVSC this isn't the case. It works as expected on Clang and gcc, so I'd assume this is a bug in MSVC. Or is there some UB in the code? A far as I know, UB isn't allowed in constant expressions, right? Are there any circumstances under which a function can yield different results in constexpr and non-constexpr execution? #include <iostream> #include <ranges> #include <array> struct Edge { int from{}; int to{}; }; constexpr auto node_input_edges(auto& edges, int id) { return edges | std::views::filter([id](const Edge& e) { return e.to == id; }); } constexpr void visit_dfs(auto& edges, int curr_node, auto func) { for (auto e : node_input_edges(edges, curr_node)) { visit_dfs(edges, e.from, func); } func(); } constexpr auto count_dfs() { std::array<Edge, 3> edges{{{0,2}, {1,2}, {2,3}}}; size_t sz = 0; visit_dfs(edges, int(edges.size()), [&]() { ++sz; }); return sz; } int main() { constexpr auto cnt_ct = count_dfs(); auto cnt_rt = count_dfs(); std::cout << "COMPILE TIME " << cnt_ct << "\n"; // 3 on MSVC, 4 on clang and gcc std::cout << "RUNTIME " << cnt_rt << "\n"; // 4 on all compilers return 0; } Compiler explorer
It looks like an issue with how MSVC treats views. Here is a somewhat ugly but equivalent code that works without views: #include <iostream> #include <ranges> #include <array> struct Edge { int from{}; int to{}; }; template<std::size_t n> constexpr auto node_input_edges(std::array<Edge, n> const& edges, int id) { std::array<Edge, n> edges_copy; auto j = 0; for (auto i = 0; i < n; ++i) { if (edges[i].to == id) { edges_copy[j] = edges[i]; ++j; } } if (j != n) { edges_copy[j] = {0, 0}; // similar to a null terminator } return edges_copy; } constexpr void visit_dfs(auto const& edges, int curr_node, auto func) { for (auto const& e : node_input_edges(edges, curr_node)) { if (e.from == 0 && e.to == 0) { // check for the null terminator break; } visit_dfs(edges, e.from, func); } func(); } constexpr auto count_dfs() { std::array<Edge, 3> edges{{{0,2}, {1,2}, {2,3}}}; size_t sz = 0; visit_dfs(edges, 3, [&]() { ++sz; }); return sz; } int main() { constexpr auto cnt_ct = count_dfs(); auto cnt_rt = count_dfs(); std::cout << "COMPILE TIME " << cnt_ct << "\n"; std::cout << "RUNTIME " << cnt_rt << "\n"; return 0; } Demo
74,090,696
74,090,810
using a const static array in constructor result in 'warning ... is used uninitialized in this function'
I am trying to understand a compiler warning. I have a simple class #pragma once #include <framework/project_definitions.hpp> #include <framework/free_rtos/free_rtos.hpp> #include <modules/net/imqtt_client.hpp> #include "mqtt_command_base.hpp" namespace application::commands { class check_alive_command : public mqtt_command_base { public: check_alive_command( modules::imqtt_client &mqtt_client, framework::free_rtos::ifree_rtos &free_rtos); int32_t execute(const uint8_t *payload, uint32_t length) override; }; } with the following implementation #include "check_alive_command.hpp" const static uint8_t _payload_buffer[10] = {}; namespace application::commands { check_alive_command::check_alive_command( modules::imqtt_client &mqtt_client, framework::free_rtos::ifree_rtos &free_rtos) : mqtt_command_base( mqtt_client, free_rtos, iobox_check_alive_command, stack_size_small, &_payload_buffer[0]) { } int32_t check_alive_command::execute(const uint8_t *payload, uint32_t length) { return modules::mqtt_error_code::ok; } } The base of check_alive_command #pragma once #include <modules/net/imqtt_client.hpp> #include <framework/free_rtos/free_rtos.hpp> namespace valinso::application::commands { class mqtt_command_base { public: mqtt_command_base( modules::imqtt_client &mqtt_client, framework::free_rtos::ifree_rtos &free_rtos, const char * command_name, const uint32_t stack_size, uint8_t *payload_buffer); void run(const uint8_t *payload, uint32_t length); virtual int32_t execute(const uint8_t *payload, uint32_t length) = 0; protected: modules::imqtt_client &_mqtt_client; framework::free_rtos::ifree_rtos &_free_rtos; const char * _command_name; const uint32_t _stack_size; uint8_t *_payload_buffer; size_t _current_payload_length = 0; bool _is_busy = false; }; } The compiler warns /home/bp/dev/iobox/firmware/app/iobox/commands/check_alive_command.cpp: In constructor 'application::commands::check_alive_command::check_alive_command(modules::imqtt_client&, framework::free_rtos::ifree_rtos&)': /home/bp/dev/iobox/firmware/app/iobox/commands/check_alive_command.cpp:15:18: warning: '*<unknown>.application::commands::check_alive_command::<anonymous>.application::commands::mqtt_command_base::_payload_buffer' is used uninitialized in this function [-Wuninitialized] 15 | &_payload_buffer[0]) Why? How?? It's not even true, right? Startup code which initialized .data section, runs before my __libc__init_array. So why would this be uninitialized? More importantly, how can I fix this warning? Personally more important: why does it give this warning?
It's simple, really. You have two variables named _payload_buffer. One is your static constant, and the other one is one of mqtt_command_base's members. When you refer to _payload_buffer in check_alive_command's constructor, you're really using the member, not the static variable. So of course, it is uninitialized at this time. Your compiler is right. As for the fix, either rename one of those two, or tell the compiler you want the global one with ::: mqtt_command_base( mqtt_client, free_rtos, iobox_check_alive_command, stack_size_small, &::_payload_buffer[0]) // <-- :: right there It's up to you.
74,090,771
74,090,928
How to check whether an element exists in an array as in Python using "in"
A user has to select a choice from the menu, and the program's goal is to check whether the user has selected a valid choice or not. In python I would run a while loop and compare them using "in": (userChoice in validChoices). How do I do that in C++ using a while loop? Valid choices are stored in this variable: const char validChoices[12] = {'P', 'p', 'A', 'a', 'M', 'm', 'S', 's', 'L', 'l', 'Q', 'q'} The program asks the user for input and stores it in a char variable: char userChoice {}; std::cin >> userChoice; If the choice is invalid, the program should say "Unknown selection, please try again" and ask again for the input until the user selects a valid option. Appreciate the help in advance!! Been struggling with it a lot. Current attempt: bool isValidChoice = true; while (isValidChoice) { char userChoice {}; std::cout << "Select a choice: "; std::cin >> userChoice; if () { std::cout << "You have selected: " << userChoice << std::endl; isValidChoice = false; } else { std::cout << "Unknown selection, please try again" << std::endl; }
You can simply call auto it = std::find(std::begin(validChoices), std::end(validChoices), userChoice); by checking statement if(it != validChoices.end()) it means that your choice have been found in the validChoices, because userChoice value have been found before validChoices end structure iterator. If it would be validChoices.end() that would mean that it just couldn't be found.
74,090,931
74,090,952
Can't add numbers to an existing index in an array
I'm new to C++ and can't understand what is wrong here. This code was made for problem 339A from CodeForces. I get an unsorted sum str input with numbers from 1-3 (Ex. 1+2+3+2+1). I'm trying to find the total ocurrences of every number, but when trying to sum to an index of the array, it just overflows or gives me an unrelated number. Why is this so? Example Input: 1+2+3+2+1 Output of array: [0, -13008, 5] I have the following code: #include <iostream> using namespace std; int main(){ string s; int arr[3]; cin >> s; for(int i=0; i<s.size(); i+= 2){ if(s[i] == 1){ arr[0] += 1; } else if(s[i] == 2){ arr[1] += 1; } else{ arr[2] += 1; } } ...
For starters you need to initialize the array int arr[3] = {}; And you need to compare characters like for example if(s[i] == '1'){ If you are sure that s[i] contains only characters '1'-'3' then instead of the if statements you could write for example ++arr[s[i] - '1']; or you could use only one if statement if ( '1' <= s[i] && s[i] <= '3' ) { ++arr[s[i] - '1']; }
74,091,075
74,091,125
C++ generating a variable number of nested FOR-loops
I have a struct containing a vector of elements: struct SomeStruct { std::vector<Element> vec; }; each Element contains a container: struct Element { Container m_container; }; The vector can contain 3, 4 or 5 Elements. This is guaranteed. If there are 3 items, the next stage contains a series of 3 nested for loops (see below). A vector with 4 elements required 4 loops, 5 -> 5 loops etc. There will only be 3, 4 or 5 loops. I have to omit some code but the logic within the loops concludes with multiplying the doubles together and calculating a minimum. So the inner-most loop needs access to the local variables from the earlier loops. for(const auto& x : vec[0].m_container) { const double some_calc = some_func(x); for(const auto& y : vec[1].m_container) { const double some_calc_2 = some_func(y); for(const auto& z : vec[2].m_container) { const double some_calc_3 = some_func(z); // TODO need a way to generate 4th and 5th loops if required // Logic processing data from the 3 loops const double a_calculation = some_calc * some_calc_2 * some_calc_3; double a_min = some_calc; a_min = std::min(a_min, some_calc_2); a_min = std::min(a_min, some_calc_3); } } } Is there a way I can automate/generate these nested FOR Loops, depending on the size of the vector? I was thinking of something templated like this: if(struct.vec.size() == 3) { the_answer<3>(struct.vec); } else if(struct.vec.size() == 4) { the_answer<4>(struct.vec); } else { the_answer<5>(struct.vec); }
You can solve solve this problems most of the times with recursion. so void loop(int n,const vector<double>& vec, vector<double> outer_vars){ if (n!=vec.size()){ for(const auto& z : vec[n]){ outer_vars.push_back(some_func(z)); loop(n+1,vec,outer_vars); } } }
74,091,297
74,091,348
How to access to the actual type of a template specialization type parameter
Suppose the following structures: // struct 'A' struct A { static std::string toString() { return "A"; } }; // struct 'B' inherits 'A' struct B : public A { static std::string toString() { return "B"; } }; // struct 'X' struct X { static std::string toString() { return "X"; } }; then the following template class: template <typename T> // Common 'ToString' template type: class ToString { public: static void print() { std::cout << "Other type: " << T::toString() << "\n"; } }; and one specialization for A: template <> class ToString<A> { // Specialization of 'ToString' for type 'A' or subtypes of 'A': public: static void print() { std::cout << "Subtype of A: " << A::toString() << "\n"; } }; The result of: int main(void) { ToString<X>::print(); // OK: invokes 'template<T> ToString::print()' ToString<A>::print(); // OK: invokes 'ToString<A>::print()' ToString<B>::print(); // KO: I want it invokes 'ToString<A>::print()' } is Other type: X Subtype of A: A Other type: B I have 2 questions: 1: Since B inherits A, why the output of ToString<B>::print() is not something like: Subtype of A: ... 2: In ToString<A>::print() function, i wrote ... << A::toString() << .... What can I write instead of the (by the way redundant) A to refer to the actual type of the template type parameter which is A itself or any of its subtypes, so that the output for B would be: Subtype of A: B Thanks
Specialization for A requires an exact match, but A and B are different types. Inheritance is irrelevant here. Try to make a specialization more generic: template<typename T, typename = std::bool_constant<true>> struct ToString { // ... }; template<typename T> struct ToString<T, std::bool_constant<std::is_base_of_v<A, T>>> { static void print() { std::cout << "Subtype of A: " << T::toString() << "\n"; } }; Now the output is: Other type: X Subtype of A: A Subtype of A: B The idea is similar to std::void_t trick, which is explained here. Demo. In C++20, you can also do this: template<typename T> struct ToString { // ... }; template<std::derived_from<A> T> struct ToString<T> { static void print() { std::cout << "Subtype of A: " << T::toString() << "\n"; } };
74,091,601
74,092,362
How to use QGroupBox and QCheckBoxes to one check another?
I'm trying to understand how to use signals to when one QCheckBox be checked it uncheck all other checkboxes present in the same QGroupBox class GroupBox : public QGroupBox { public: GroupBox(QWidget *parent = nullptr) : QGroupBox(parent) { } public slots: void uncheck(); }; class CheckBox : public QCheckBox { public: CheckBox(QWidget *parent = nullptr) : QCheckBox(parent) { connect(this, SIGNAL(checked()), this, SLOT(checked())); } public slots: void checked() { qDebug() << "checked"; } }; When I click on one of the checkboxes it didn't go to the function checked().
QCheckBox inherits from QAbstractButton You should use clicked or stateChanged signal instead of checked. e.p. connect(this, SIGNAL(stateChanged(int)), this, SLOT(checked(int))); Btw; if using a modern Qt version, you should ditch the SIGNAL and SLOTS macros and instead use the new connect() syntax that's checked at compile time. Refer: New Signal Slot Syntax e.p. connect(this, &QCheckBox::clicked, this, &CheckBox::checked);
74,091,630
74,091,702
Efficient Way to draw many individual pixels to a screen in SDL2
I'm currently working on something in C++ using SDL2 that requires being able to draw a lot of individual pixels with specific color values to the screen every update. I'm using SDL_RenderDrawPoint just to make sure my program works but I'm sure the performance on that is terrible. From a cursory search it seems like using a texture that is the size of my window would be fastest by using SDL_UpdateTexture and updating it with a vector of pixels with my desired pixel values with a default of {0,0,0,0} RGBA value for any pixel not changed. However every attempt I've had at writing it fails and I'm not sure where my misunderstandings lie. This is my current code that attempts to draw a specific RGBA color value to a specific x,y coordinate in my texture. I assume the part of the buffer I'm accessing using my x,y values is incorrect but I'm unsure how to make it correct if so. Any help is appreciated including suggestions on how to efficiently do this without a texture if there's a better way. SDL_Texture* windowTexture = SDL_CreateTexture(render, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_STREAMING, screenWidth, screenHeight); unsigned int* lockedPixels = nullptr; std::vector<int> pixels(screenHeight*screenWidth*4, 0); int pitch = 0; int start = (y * screenWidth + x) * 4; pixels[start + 0] = B; pixels[start + 1] = G; pixels[start + 2] = R; pixels[start + 3] = A; SDL_UpdateTexture(windowTexture, nullptr, pixels.data(), screenWidth * 4);
The pixel format RGBA8888 means that each pixel is a 32 bit element with each channel (i.e. red, green, blue or alpha) taking up 8 bits, in that order. You may want to declare pixels as containing the type "32 bit unsigned integer". An unsigned int is typically 32 bits, but it may also be larger. std::vector<Uint32> pixels(screenHeight*screenWidth, 0); // Note: no *4 The individual R, G, B, A values (which should each be 8 bit unsigned integers) can be combined into one pixel by using shifts and bit-wise ORs: int start = y * screenWidth + x; // Note: no *4 pixels[start] = (R << 24U) | (G << 16U) | (B << 8U) | A; Lastly, you may want to not hardcode the last parameter of SDL_UpdateTexture (i.e. pitch). Instead, use screenWidth * sizeof(Uint32). The implementation above is basically a direct implementation of "RGBA8888" and allows you to access individual pixels. Alternatively, you could also declare an array of four times the size containing 8 bit unsigned integers. Then, the first four indices would correspond to the R, G, B, A values of the first pixel, the next four indices would correspond to the R, G, B, A values of the second pixel, etc. Which one is faster would depend on the exact system and use-case (whether the most common operations are on pixels or individual channels). PS. Instead of Uint32 you could also use C++'s own std::uint32_t from the cstdlib header.
74,091,674
74,091,770
(C++) Variables in header warned as unused even though they definitely are
Not an emergency because the code still works, I'm mainly just curious. I'm using raylib to make an RPG. I wrote a function that changes the displayed rotational sprite depending on the last direction the player moved. If you're unfamiliar with raylib, textures are a variable type which must be initialized with the function LoadTexture(const char *fileName). This is taken care of at program start by another function I wrote. For some reason, g++ is warning me that these variables are unused, even though they clearly are, due to the fact that the sprite is being rendered. This is my declaration, in draw.h: // Sprite variables static Texture pUp; // Player facing up static Texture pDown; // Player facing down static Texture pLeft; // Player facing left static Texture pRight; // Player facing right I use a function PSetSprite(Dir pDir) which takes the current direction of the player as an argument and returns the correct rotational sprite. Texture PSetSprite(Dir pDir) { static Texture pSprite = pDown; switch (pDir) { case UP: pSprite = pUp; break; case DOWN: pSprite = pDown; break; case LEFT: pSprite = pLeft; break; case RIGHT: pSprite = pRight; break; case UP_LEFT: pSprite = pLeft; break; case UP_RIGHT: pSprite = pRight; break; case DOWN_LEFT: pSprite = pLeft; break; case DOWN_RIGHT: pSprite = pRight; break; default: break; } return pSprite; } This is then passed to the player object with player.Draw(const Texture pSprite) and drawn to the screen. Deleting the variables obviously breaks my program, so what gives? For those who asked, I am using version 12.2.0 of g++, and the specific error is "'pUp' defined but not used," x4 for each rotational sprite.
The static keyword has different meanings depending on where it is used. Marking a variable at namespace scope as static (in contrast to block or class scope) gives it internal linkage, meaning that there will be a different variable of the same name and type in each translation unit including the declaration (i.e. each .cpp file including the header). So the compiler is probably warning you that you are not using the variables in some translation unit where you also include the header but do not access them. Since each translation unit has an independent set of these variables, the compiler is correct to warn you that you are not using those instances of the variables. If these variables are only supposed to be used in one translation unit, then they shouldn't be declared in a header shared with other translation units, but instead either in the .cpp directly or a separate header specific to that .cpp. If the variables are intended to be accessed from multiple translation units, then they cannot be declared static. Instead of static the keyword inline can be used, which will give them external linkage so that they are the same variables in each translation unit, and at the same time the inline keyword allows the definitions of the variables to be included in multiple translation units (usually, without inline, you would need to declare them in the header with extern and then define them in only one translation unit), assuming that each definition is identical (e.g. included from the same header).
74,091,977
74,091,997
Why do we need two constructors while doing operator overloading?
I saw a code in sololearn platform(C++ course) and it is about defining overloading for operator +. you can see the code below: #include <iostream> using namespace std; class Account { private: int balance=0; int interest=0; public: Account() {} Account(int a): balance(a) { interest += balance/10; } int getTotal() { return balance+interest; } Account operator+(Account &obj){ Account OBJ2; OBJ2.balance=this->balance + obj.balance; OBJ2.interest=this->interest +obj.interest; return OBJ2; } }; int main() { int n1, n2; cin >> n1 >> n2; Account a(n1); Account b(n2); Account res = a+b; cout << res.getTotal(); } My question is: why do we need to keep two constructors in class "Account"? I don't understand the reason of having the default constructor( the first one without any parameter). I tried to delete it but then the code does not work. Thank you
Look at your operator+. The first line is: Account OBJ2; Without a default constructor, that line is illegal. You could avoid the need for the default constructor there by using the other constructor: Account operator+(const Account &obj) const { // Added const for correctness Account OBJ2(this->balance + obj.balance); // Create with constructor taking int OBJ2.interest = this->interest + obj.interest; // May be avoidable if constructor calculation known to be valid return OBJ2; }
74,092,324
74,092,441
How to using regex match all content before these specific symbol in cpp?
I want to find a front(first) part before some symbols in a string. For example, "ABC, ZXC", "AB.QWE,CV", I want to get the result, "ABC" and "AB". By the way, if there is some chinese character in this sentence, like "1月1日,天气晴" how to get the front part(1月1日)? It is easier to reach in Python by import re front_part = re.findall(r'(.*?)[.,]', content)[0] if re.findall(r'[.,]',sentence) else content #if it didn't find symbols, then return the whole content. However, I tried to use following codes in Cpp but it still returns the whole content: #include<regex> #include<string> #include<iostream> int main() { std::string content = "AB.AC"; std::string front_part; std::smatch frt_pt_sm; std::regex frt_pt_patt(".*[.,]"); if (std::regex_match(content, frt_pt_sm, frt_pt_patt)) { for(unsigned i = 0;i < frt_pt_sm.size(); ++i) { std::cout<< frt_pt_sm[i] << std::endl; } front_part = frt_pt_sm[0]; } return 0; } I am a novice in cpp so any suggesion is helpful for me!
C++ regexes don't have an equivalent to the (.*?) that you're using in Python. In C++ you'll want to use something like: [^.,] to match the part up to (but not including) the first . or ,. On the other hand, given how simple of a pattern you're looking for, you could easily forego using regexes altogether: std::string input = "AB.QWE,CV"; auto pos = input.find_first_of(".,"); auto front = input.substr(0, pos);
74,092,366
74,092,423
range-expression of range based for loop in C++
I am trying to pass a pointer of vector to range based for loop for its range-expression. Here is the syntax of range based for loop: attr(optional) for ( init-statement(optional) range-declaration : range-expression ) loop-statement Referenced from cppreference.com: range-expression is evaluated to determine the sequence or range to iterate. Each element of the sequence, in turn, is dereferenced and is used to initialize the variable with the type and name given in range-declaration. begin-expr and end-expr are defined as follows: If range-expression is an expression of array type, then begin-expr is __range and end-expr is (__range + __bound), where __bound is the number of elements in the array (if the array has unknown size or is of an incomplete type, the program is ill-formed) If range-expression is an expression of a class type C that has both a member named begin and a member named end (regardless of the type or accessibility of such member), then begin-expr is __range.begin() and end-expr is __range.end(); Otherwise, begin-expr is begin(__range) and end-expr is end(__range), which are found via argument-dependent lookup (non-ADL lookup is not performed). I defined begin and end and expect them to be used for begin-expr, to dereference the pointer, but failed. Here is my codes: #include <iostream> // std::cout #include <vector> using namespace std; vector<int>::iterator begin(vector<int> *a) { return a->begin(); } vector<int>::iterator end(vector<int> *a) { return a->end(); } int main() { vector<int> v = {1,2,3,4}; vector<int> *p = &v; for (auto i : p) { cout << i << endl; } return 0; } I am still getting the below compile error: Invalid range expression of type 'vector<int> *'; did you mean to dereference it with '*'? Is there anything I missed here?
Otherwise, begin-expr is begin(__range) and end-expr is end(__range), which are found via argument-dependent lookup (non-ADL lookup is not performed). begin() and end() are looked up only via ADL. For pointers, it works like this: For arguments of type pointer to T or pointer to an array of T, the type T is examined and its associated set of classes and namespaces is added to the set. The only namespace associated with std::vector<int> is namespace std, so that's where begin() and end() will be looked up. Putting begin() and end() into namespace std makes the code work, but adding new declarations into std causes undefined behavior (with a few exceptions), and shouldn't be done.
74,093,442
74,093,725
How to iterate over an integer range when you don't know if it is in increasing or decreasing order?
I am trying to iterate over a range in one loop and NOT using below two for-loops: if (firstIndex <= secondIndex) for (int i = firstIndex; i <= secondIndex; i++) {...} else for (int i = firstIndex; i >= secondIndex; i--) {...} I considered using boost::irange but it does not cover secondIndex index. Update: I need to preserve the order and CANNOT swap indices.
In a contrived way, you can use for (int i= first; first >= second ? (i <= second) : (i >= second); i+= first >= last ? +1 : -1) A variant is possible with a increment variable and multiplies. I don' like it much. int inc= first >= second ? +1 : -1; for (int i= first; inc * i <= inc * second; i+= inc)
74,094,006
74,094,159
C++: Nested dictionaries with unordered_maps
I'm trying to write some code that will allow me to create a dictionary with the unordered_map object in C++. It will basically look like string1 string2 int_vec1 string3 int_vec2 ... i.e. It's a dictionary of string and integer-vector pairs, indexed by strings. I have the following code of a simplified example to illustrate: #include <chrono> #include <iostream> #include <vector> #include <map> #include <fstream> #include <ctime> #include <string> #include <unordered_map> int main(int argc, char **argv) { std::string key_0 = "key_0"; std::string key_01 = "key_01"; std::string key_02 = "key_02"; std::string key_1 = "key_1"; std::string key_11 = "key_11"; std::string key_12 = "key_12"; std::string key_13 = "key_13"; std::vector<int> val_01 = {1,2,3,4}; std::vector<int> val_02 = {1,2,3,4}; std::vector<int> val_11 = {1,2,3,4}; std::vector<int> val_12 = {1,2,3,4}; std::vector<int> val_13 = {1,2,3,4}; std::unordered_map<std::string, std::unordered_map<std::string, std::vector<int>>> my_dict; my_dict.insert({key_0, std::pair<std::string, std::vector<int>>(key_01, val_01)}); } However, when I compile this using gcc version 11.2.0, I get the following error test_make_nested_unordered_map.cpp:25:17: error: no matching function for call to ‘std::unordered_map<std::__cxx11::basic_string<char>, std::unordered_map<std::__cxx11::basic_string<char>, std::vector<int> > >::insert(<brace-enclosed initializer list>)’ 25 | my_dict.insert({key_0, std::pair<std::string, std::vector<int>>(key_01, val_01)}); | ~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The code seems fine to me. But I don't know why it isn't working. I would greatly appreciate some help with this. My actual code is more complicated, but this is just meant to be a simplified reproducible example. Thanks for the help Edit Thanks to user 273K for the answer. I was able to get it working closer to what I expected: This code runs without issue #include <chrono> #include <iostream> #include <vector> #include <map> #include <fstream> #include <ctime> #include <string> #include <unordered_map> void print_string_vec2(std::vector<int> vec) { for (auto s : vec) { std::cout << s << " "; } std::cout << std::endl; } int main(int argc, char **argv) { std::string key_0 = "key_0"; std::string key_01 = "key_01"; std::string key_02 = "key_02"; std::string key_1 = "key_1"; std::string key_11 = "key_11"; std::string key_12 = "key_12"; std::string key_13 = "key_13"; std::vector<int> val_01 = {1,2,3,4}; std::vector<int> val_02 = {1,2,3,4}; std::vector<int> val_11 = {1,2,3,4}; std::vector<int> val_12 = {1,2,3,4}; std::vector<int> val_13 = {1,2,3,4}; std::unordered_map<std::string, std::unordered_map<std::string, std::vector<int>>> my_dict; my_dict.insert({key_0, {{key_01, val_01}}}); my_dict[key_0].insert({key_02, val_02}); my_dict.insert({key_1, {{key_11, val_11}}}); my_dict[key_1].insert({key_12, val_12}); my_dict[key_1].insert({key_13, val_13}); for (auto& u : my_dict) { for (auto& v : u.second) { std::cout << "(" << u.first << "," << v.first << "): "; print_string_vec2(v.second); } } } When run, it outputs (key_1,key_13): 1 2 3 4 (key_1,key_12): 1 2 3 4 (key_1,key_11): 1 2 3 4 (key_0,key_02): 1 2 3 4 (key_0,key_01): 1 2 3 4
There is no conversion from std::pair to std::unordered_map. You seem to wish my_dict.insert({key_0, {{key_01, val_01}}}); The inner braces are initializer list for the inner unordered map with the pair initializer.
74,094,219
74,094,534
C++ use RAII objects with comma operator?
I have a lock class like this: class Mutex { Guard lock(); // acquire the lock } class Guard { ~Guard(); // release the lock } This is how I'm using it now: Mutex m_mutex; T m_data; T get_data() { auto guard = m_mutex.lock(); return m_data; } But I'm thinking is it safe / good practice to write like this? T get_data() { return (m_mutex.lock(), m_data); }
It is mostly safe. The order of destruction has been clarified with CWG 1885, so that the temporary object materialized from the m_mutex.lock() call will be destroyed only after the result object of the function has been initialized. The built-in comma operator also guarantees that the left-hand operand is sequenced before the right-hand one. There is however a problem if there is a operator, overload for T. In that case the expression could have any effect. To avoid issues with that you need to explicitly cast the lock expression to void, which forces use of the built-in comma operator: return ((void)m_mutex.lock(), m_data); Whether this is good practice goes into opinion territory, but I think there are definitively going to be many developers who will be confused by this construct for a moment (even if they know how the comma operator and lifetimes work) and it doesn't really save you anything. (Having to choose an unused name is annoying, but not a real issue.)
74,094,593
74,094,745
Conditional includes of header and implementation files containing functions with identical names
When I try to compile the following 6 files all together, I get "multiple definition of `funcX(float, float)'" error. If I remove "includeB.h" and "includeB.cpp" from the folder, then remaining 4 files are compiled. What am I doing wrong? Appreciate your help. Thanks in advance! Assume my common.h file looks like this: #ifndef COMMON_H #define COMMON_H // Uncomment needed Configuration Option #define CONFIG 1 // Hardware Option 1 //#define CONFIG 2 // Hardware Option 2 #endif and my main.cpp looks like this: #include "common.h" #if CONFIG == 1 #include "includeA.h" #else #include "includeB.h" #endif void main() { // put your main code here, to run repeatedly: float x; float a = 3.0; float b = 5.7; x = funcX(a, b); } My includeA.h file looks like this: #ifndef INCLUDEA_H #define INCLUDEA_H float funcX(float a, float b); #endif and corresponding implementation file includeA.cpp: #include "includeA.h" float funcX(float a, float b) { return a * b; } My other header file includeB.h looks like: #ifndef INCLUDEB_H #define INCLUDEB_H float funcX(float a, float b); #endif and corresponding to it the implementation file includeB.cpp: #include "includeB.h" float funcX(float a, float b) { return a + b; }
You can't have two definitions for the same function (funcX here). Two solutions: set up your build system so that only one of includeA.cpp or includeB.cpp is linked to the executable. add an #include "common.h" in includeA.cpp and includeB.cpp and compile only one version of funcX depending on the value of CONFIG. In both case, I'd suggest considering having only one include.h which would contains declarations independent of CONFIG and include "common.h" and then includeA.h or includeB.h depending on CONFIG for the dependent part.
74,094,757
74,097,489
In what cases boost::asio::ip::tcp::socket::read_some does not read all of the requested number of bytes?
According to the documentation basic_stream_socket::read_some "…operation may not read all of the requested number of bytes". What does it actually mean? Let's assume following scenario: we want to write a client which sends commands to a server and the server responds with lines of printable ASCII characters, each line ending with CRLF. Maximum line/response length is N bytes, including ending CRLF. We have the following code: boost::asio::ip::tcp::socket socket; std::array<char, N> inpbuff; […] socket.read_some(boost::asio::buffer(inpbuff, N)); It's obvious that if the response length is shorter than N, basic_stream_socket::read_some "may not read all of the requested number of bytes". But are there other cases? What about issues with underlying TCP/IP such as packet fragmentation or delays due to packet loss/out-of-order delivery? In other words, may I safely assume that the code above always reads the whole line/response? I have seen an implementation which makes such assumption but I am not sure if it is correct.
read_some reads what is available, until the buffer supplied is full. What is available is dependent on the TCP stacks and intermediate hardware. In general the timing and fragmentation of TCP packets can NOT be relied on. So, so code that does rely on it is probably flawed¹. The good news is that the docs you quoted go on and tell you how fix it: The read_some operation may not read all of the requested number of bytes. Consider using the read function if you need to ensure that the requested amount of data is read before the blocking operation completes. Let me add that there is also another, more highlevel, composed read operation that you can often use to great effect: async_read_until or read_until
74,094,760
74,094,804
When is it safe to leave out a const from a function's parametrization?
Many times I write C++ functions I seem to use many more const modifiers than other folks. For example, I write Excel .xlsx files and I use LibXL library for this, and the documentation mentions a function like this: bool writeNum(int row, int col, double value, Format* format = 0) I happened to inherit this function and my signature looks like this: bool XLAPIENTRY writeNum(const int row, const int col, const double value, IFormatT<wchar_t> * format = 0); Note the const ints for the row and the column. Question: is it safe to leave out const for ints? (It's obviuos that for pointers, leaving out const for pointers is dangerous, but doing something a local copy of an int is not that dangerous). Note that the original header containing writeNum function doesn't mention const-ing the ints, too. Why is here the const modifiers left out?
In declaration (as opposed to definition), the top-level1 const on a parameter has no effect. Arguably, it's an implementation detail of the function, that shouldn't appear in the declaration (it adds clutter, yet doesn't provide any new information for the caller). Note that const int x and int *const x are top-level const, while const int * and const int & are not, so the latter can't have its const removed. In definition, you can include the const if it helps you as the implementer of the function (so you don't change the parameter accidentally). 1 "Top-level const" means "actually const", as opposed to e.g. merely being a pointer to const. You can check this property with std::is_const_v. E.g.: std::is_const_v<const int> == true (const integer) std::is_const_v<const int *> == false (non-const pointer to const integer) std::is_const_v<int *const> == true (const pointer to non-const integer) std::is_const_v<const int **> == false (non-const pointer to non-const pointer to const integer) std::is_const_v<int *const *> == false (non-const pointer to const pointer to non-const integer) std::is_const_v<int **const> == true (const pointer to non-const pointer to non-const integer)
74,095,194
74,095,248
Can not understand the c++ code about deleting punctuations
This is a piece of code that I found online, basically, it helps me to erase all the punctuation in a string. for(size_t i = 0; i<text.length(); ++i) if(ispunct(text[i])) text.erase(i--, 1); Like in the sentence: "hello, I am John". It will delete the comma. But I do not understand why in the code: text.erase(i--, 1); I do not understand why it delete the text[i--](which is o in this case), but when the code run, it works perfectly and does not erase "o". I know that I misunderstand that part. Can somebody explain to me about that?
++i pre- in/decrement will increment i before using it, so if i is 1 it will first update it to 2 and than use it. i-- pos- in/decrement will use i before decrementing it, so if i is 5 it will use 5 and than update it to 4
74,095,621
74,095,712
function to returning reference of iterator of object
I would like to write a function to returning reference of iterator of an map entry in order to update the value of the entry. However, it fails at compile stage #include <map> #include <iostream> using namespace std; pair<int, string>& map_find(map<int,string>& m, int k){ return *(m.find(k)); } int main() { map<int,string> m; // insert an entry m.insert(make_pair<int,string>(128490,"def")); // search entry by key auto e = map_find(m,128490); cout << e.first << e.second<<endl;; e.second = "abc"; // Update value // verify if the entry is updated e = map_find(m,128490); cout << e.first << e.second<<endl;; return 0; } main.cpp: In function ‘std::pair<int, std::__cxx11::basic_string<char> >& map_find(std::map<int, std::__cxx11::basic_string<char> >&, int)’: main.cpp:15:12: error: invalid initialization of reference of type ‘std::pair >&’ from expression of type ‘std::pair >’ return *(m.find(k)); ^~~~~~~~~~~~
The value type of std::map<Key, Value> is std::pair<const Key, Value>, not std::pair<Key, Value>. There are also useful member type aliases. #include <map> #include <iostream> using MyMap = std::map<int, std::string>; MyMap::reference map_find(MyMap& m, int k){ return *(m.find(k)); } int main() { MyMap m; m.emplace(128490,"def"); auto e = map_find(m,128490); std::cout << e.first << e.second << std::endl; // Does not update the string in the map, because e is a copy. e.second = "abc"; e = map_find(m,128490); std::cout << e.first << e.second << std::endl; return 0; }
74,096,106
74,096,904
How to measure the time elapsed since the last message received from a datagram socket in Poco C++?
My code monitors a datagram socket (implemented in the Poco framework), and I'd like to get notified if there were no messages received after a certain time. I have an infinite loop to monitor the socket, but the loop stops at receiveFrom() function, if no messages were received. Here is the code: #include <iostream> #include <string> //Poco includes #include "Poco/Net/DatagramSocket.h" #include "Poco/Net/SocketAddress.h" int port = 5000; Poco::Net::SocketAddress sa(Poco::Net::IPAddress(), port); Poco::Net::DatagramSocket dgs(sa, true); char buffer[1024]; for (;;) { int n = dgs.receiveFrom(buffer, sizeof(buffer)-1, sender); buffer[n] = '\0'; std::string line = buffer; //Do something with the message };
You should set a timeout on your Poco socket. Poco::Timespan wait_time( 10000 ); // microseconds // from header file Poco/Net/Socket.h sa.getReceiveTimeout( wait_time ) Then check the number of bytes returned by receiveFrom(..) is > 0 or check for a timeout exception. Use this opportunity to do your other work.
74,096,474
74,096,938
Conversion from char* to std::string gives wrong symbols
My code is: std::string get_time() { char buf[20]; std::time_t timestamp = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); strftime(buf, 20, "%d.%m.%Y %H:%M:%S", std::gmtime(&timestamp)); std::cout<<buf<<std::endl; return std::string(buf, 20); } ... auto timestamp = get_time().c_str(); std::cout<<timestamp<<std::endl; It should return current datetime in string format. But what I get is: 17.10.2022 11:12:46 1!`u�I��22 11:12:46 So, the conversion beween char* and string works wrong. How can I fix it? Thanks in advance!
First of all, get_time() returns a std::string. Because nothing references this string, it gets deleted at the end of the line. Then, calling get_time().c_str() keeps a pointer to that string (see std::basic_string<CharT,Traits,Allocator>::c_str on cppreference). However, that string isn't guaranteed to exist. Other processes have overwritten some of that memory, using it, and that is why you get those characters. You don't need to call get_time.c_str(), you can just output the std::string directly: std::string get_time() { char buf[20]; std::time_t timestamp = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); strftime(buf, 20, "%d.%m.%Y %H:%M:%S", std::gmtime(&timestamp)); std::cout << buf << std::endl; return std::string(buf, 20); } ... auto timestamp = get_time(); std::cout << timestamp< < std::endl;
74,096,612
74,096,720
How to initialize nested struct in C++?
Let's say I have following declaration in the C++: struct Configuration { struct ParametersSetA { float param_A_01; float param_A_02; float param_A_03; } parameters_set_A; struct ParametersSetB { float param_B_01; float param_B_02; } parameters_set_B; }; Then somewhere in the code I have following definition: Configuration config = { .parameters_set_A = { .param_A_01 = 1.0f, .param_A_02 = 2.0f, .param_A_03 = param_A_01 + param_A_02; }, .parameters_set_B = { .param_B_01 = 0.50f, .param_B_02 = 0.75f } }; My question is whether the initialization (especially as far as the param_A_03 item in the nested struct ParametersSetA) I have used above is correct in the C++?
The problem is that we can't use any of the unqualified names param_A_01 or param_A_02 or an expression that involves any of the two like param_A_01 + param_A_02 as initializer forparam_A_03. Additionally, you have incorrectly put a semicolon ; after param_A_01 + param_A_02 instead of comma , . I've corrected both of these in the below shown modified program: Method 1 //create constexpr variables constexpr float A1 = 1.0f; constexpr float A2 = 2.0f; Configuration config = { .parameters_set_A = { .param_A_01 = A1, .param_A_02 = A2, //--------------vv---vv---->use those constexpr variable(also semicolon is removed from here) .param_A_03 = A1 + A2 }, .parameters_set_B = { .param_B_01 = 0.50f, .param_B_02 = 0.75f } }; Working demo Method 2 Other option is to use qualified names like config.parameters_set_A.param_A_01 and config.parameters_set_A.param_A_02 as shown below: Configuration config = { .parameters_set_A = { .param_A_01 = 1.0f, .param_A_02 = 2.0f, //--------------vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv--->qualified name used here .param_A_03 = config.parameters_set_A.param_A_01 + config.parameters_set_A.param_A_02 }, .parameters_set_B = { .param_B_01 = 0.50f, .param_B_02 = 0.75f } }; Working demo
74,096,736
74,097,492
Convert int to UIntPtr in C#
Thanks in advance. In the following piece of simple code, the model.Count is an System.Int32 integer which I get from the a third party library named Xilium.CefGlue (v107). I iterate over this integer to get the value based on the index. indexCollection = cefMenuModel.Count; for(int x=0;x<indexCollection;x++) { var value = GetCommandIdAt(x); } In the latest version of CefGlue library, The cefMenuModel.Count value has been changed from System.Int32 integer to UIntPtr and since then I am finding type conversion and '<' operator cannot be applied on UIntPtr compile time error messages. The GetCommandIdAt(x) in the older version of C++ library took parameter as an integer but now in the latest version it is expecting the parameter as UIntPtr. What change can I make in my above piece code to change the int type to UIntPtr. Basically I want to iterate over a collection of UIntPtr that I receive from cefMenuModel.Count and pass that UIntPtr value to GetCommandIdAt(x) ? The Xelium.CefGlue expects the GetCommandIdAt as: namespace Xilium.CefGlue { [NullableAttribute(0)] [NullableContextAttribute(1)] public sealed class CefMenuModel : IDisposable { ~CefMenuModel(); // // Summary: // Returns the number of items in this menu. [NativeIntegerAttribute] public UIntPtr Count { get; } // Summary: // Returns the command id at the specified |index| or -1 if not found due to invalid // range or the index being a separator. public int GetCommandIdAt([NativeIntegerAttribute] UIntPtr index); } }
Assuming that the UIntPtr values will be in the range of a 32-bit integer (which I assume they must be, because you can't address more than 2^31 items in an array in C#), then you can just freely cast between a UIntPtr and an int: UIntPtr uip1 = new UIntPtr(34234); Console.WriteLine(uip1); // 34234 int i = (int) uip1; // Cast from UIntPtr to int Console.WriteLine(i); // 34234 UIntPtr uip2 = (UIntPtr) i; Console.WriteLine(uip2); // 34234 Also note that you can now use the nuint type instead of UIntPtr and the nint type instead of IntPtr: nuint uip1 = 34234; Console.WriteLine(uip1); // 34234 int i = (int) uip1; // Cast from nuint to int Console.WriteLine(i); // 34234 nuint uip2 = (nuint) i; Console.WriteLine(uip2); // 34234 IMPORTANT: It's totally weird that the authors of the library would make this change. The size of a UIntPtr (and nuint) is 64 bits when running as x64 and 32 bits when running as x86. This means that casting to int will fail on an x64 build if the value exceeds 2^31. As I said earlier, a value of greater than 2^31 is NOT supported for array or list indexing in C#, so if it exceeds that value you're stuffed either way.
74,097,013
74,126,107
C++/CLI usage with unmanaged code - Boost, <future>
I am trying to compile a C++ library for use with C# on Windows (the library is Vanetza). The library uses CMake, I am building from Microsoft Visual Studio Community 2022 (64-bit). I can build the library as shared DLL no problem. For use with C#, I thought of compiling the library as C++/CLI (common language runtime support enabled). At first, I could not compile it because the project uses Boost, but some compilation issues were solved by surrounding every Boost include with #pragma managed(push, off) and #pragma managed(pop). Issue which blocks me now is that <future> header cannot be used with C++/CLI - I am getting this compilation error from lot of different places: Severity Code Description Project File Line Suppression State Error C1189 #error: <future> is not supported when compiling with /clr or /clr:pure. geonet C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.33.31629\include\future 13 and I cannot solve this. I think that some Boost module that is used needs this header. Is there any solution to this or is there another approach that could be used? I need not only to get to some C++ functions of the library, but also to use some of its classes and to see some of its structures. I tried compiling the library as normal C++ and then make an interfacing C++/CLI library which would be called from C#, but the header is again used somewhere. I think that using P/Invoke (DLLImport) is impractical for me as it is only making possible to use C/C++ functions, but for classes and structures it cannot be used (as I understand it). Is only possible solution to rewrite the parts that need <future> myself using C# constructs as mentioned in this question? As per other similar questions, it seems that sometimes the project can be built such that Boost works without any problems and sometimes major code rewrite is needed. Could someone recommend me what would a usable approach would be in my case? I could use older Boost version (namely 1.58.0), but I do not know if it would help.
Write a class in c++/cli that connects to your C++ code. The code will call the router which I presume will return a future. Then in manged/cli you create a task that hooks up to that future. So you have the original code compile to a static C++ lib and link that into your managed C++/cli dll
74,097,037
74,097,180
Inheritance from STL priority_queue with custom comparator not working
I would like to inherit from STL priority queue to have some additional functionality such as: allowing removal. But I am struggling to make this work when I use custom comparators. MWE: #include <queue> template<typename T, class Container=std::vector<T>, class Compare=std::less<typename Container::value_type>> class custom_priority_queue : public std::priority_queue<T, Container, Compare> { public: // My additional functions here. }; int main() { auto pq_comp = [](const int& a, const int& b) { return a <= b; }; std::priority_queue<int, std::vector<int>, decltype(pq_comp)> pq(pq_comp); // works custom_priority_queue<int> pq_custom; // works custom_priority_queue<int, std::vector<int>, decltype(pq_comp)> pq_custom2(pq_comp); // Error return 0; } The error is: main.cpp: In function ‘int main()’: main.cpp:15:87: error: no matching function for call to ‘custom_priority_queue, main():: >::custom_priority_queue(main()::&)’ 15 | custom_priority_queue<int, std::vector<int>, decltype(pq_comp)> pq_custom2(pq_comp); // Error | ^ main.cpp:4:7: note: candidate: ‘custom_priority_queue, main():: >::custom_priority_queue(const custom_priority_queue, main():: >&)’ 4 | class custom_priority_queue : public std::priority_queue<T, Container, Compare> | ^~~~~~~~~~~~~~~~~~~~~ main.cpp:4:7: note: no known conversion for argument 1 from ‘main()::’ to ‘const custom_priority_queue, main():: >&’ main.cpp:4:7: note: candidate: ‘custom_priority_queue, main():: >::custom_priority_queue(custom_priority_queue, main():: >&&)’ main.cpp:4:7: note: no known conversion for argument 1 from ‘main()::’ to ‘custom_priority_queue, main():: >&&’
Constructors are not automatically inherited, so your class probably lacks any constructor, except the implicitly-declared ones. You can explicitly inherit all constructors of the base class: template<typename T, class Container=std::vector<T>, class Compare=std::less<typename Container::value_type>> class custom_priority_queue : public std::priority_queue<T, Container, Compare> { // inherit constructors using priority_queue::priority_queue; public: // My additional functions here. };
74,097,243
74,097,300
C2280 error attempint to reference a deleted function
The function DataContainer.initial() triggers a C2280 error. After defining a move assignment operator it works. But I am not clear why in function initial_2() it works. The obvious difference is that data_a is a local variable and data_b is a class member. Thanks for helping. #include <vector> #include <iostream> class DataTypeA { std::vector<double> data; public: // default constructor DataTypeA() {} // Move constructor DataTypeA(DataTypeA&& rhs) noexcept :data(std::move(rhs.data)) { std::cout << __FUNCTION__ << std::endl; } //DataTypeA& operator=(TypeB&& rhs) noexcept //{ // data = (std::move(rhs.data)); // return *this; //} DataTypeA(size_t width, size_t height, double default_val) { data.resize(width * height, default_val); } size_t get_size() const { return data.size(); } }; class Reader { public: Reader() {} DataTypeA read_data() { DataTypeA rtn(5, 5, 1.2); return rtn; } }; class DataContainer { DataTypeA data_b; public: DataContainer() {} void initial() { Reader rd; // this requires the copy or move assignment operator // Error C2280 'DataTypeA &DataTypeA::operator =(const DataTypeA &)': attempting to reference a deleted function data_b = rd.read_data(); } void initial_2() { Reader rd; DataTypeA data_a = rd.read_data(); std::cout << data_a.get_size(); } };
In the function initial_2, you are creating a new object of type DataTypeA from an existing object, so you can use the move constructor. However, in initial, you are assigning new data to an existing object. For this, you need to have the assignment operator. See Difference between the move assignment operator and move constructor?.
74,097,670
74,097,776
No instance of overloaded function "std::vector<_Ty, _Alloc>::erase [with _Ty=Enemy *, _Alloc=std::allocator<Enemy *>]" matches the argument list
for (auto enemy : this->enemies) { if (enemy->getHP() <= 0) { enemies.erase(enemy); } } I have a vector enemies containing multiple of Enemy* elements and i want to erase an enemy if their hp is 0 or below I write the code above and it gave me this error message: No instance of overloaded function "std::vector<_Ty, _Alloc>::erase [with _Ty=Enemy *, _Alloc=std::allocator<Enemy *>]" matches the argument list argument types are: (Enemy*) object type is: std::vector<Enemy*,std::allocator<Enemy*>> I assume that is not the right way to do it, so how? Im new in stackoverflow and im still learning english so sorry if i made mistakes EDIT: It's my almost complete code: struct enemyType { public: int type; sf::Vector2f pos; } std::vector<std::vector<enemyType>> enemyList = { { { trashMonster, sf::Vector2f(5.f * 16, 18.f * 16) } } } std::vector<Enemy*> enemies; std::vector<Enemy*>* GetEnemy(int level) { for (int i = 0; i < enemyList[level].size(); i++) { switch (enemyList[level][i].type) { case trashMonster: n_TrashMonster->setPosition(enemyList[level][i].pos); enemies.emplace_back(n_TrashMonster); break; default: std::cout << "Error to get an enemy\n"; break; } } return &enemies; } //Code in different file std::vector<Enemy*> enemies; this->enemies = *GetEnemy(lvl); for (auto enemy : this->enemies) { enemy->update(player->getCollisionBox()); //collision enemies to tilemap collision::MapCollision(*this->map.getTilesCol(), *enemy); if (enemy->getHP() <= 0) { enemies.erase(enemy); } } Didn't include that because my code is a complete mess so I was afraid people won't get the point of my question and it's my first question here
The std::vector<T>::erase function does not have a erase(T a) overload. And if you want to remove elemennts from a vector you can't iterate over them like that. I suggest a convencional loop. for (size_t i=0; i<this->enemies.size();++i){ if (this->enemies[i]->getHP()){ std::swap(enemies[i],enemies::back()); delete enemies::back();//Only if you don't free the space elsewere enemies.pop_back(); } } Edit: This will mess up the order of the vector. If you don't want that you can use erase(enemies.begin()+i) iinstead of swaping it back and removeing it
74,097,800
74,097,881
I can change the values even when I use const word with my own array class template
So I'm trying to write my own array template and everything works until i try to create a const object of my class template. in main.cpp I create the object with the copy contructor and I change it which I would expect to not work but it works. Help would be appreciated :D main.cpp # include "Array.hpp" int main( void ) { Array<int> l = 1; l.setValue(5, 0); const Array<int> abc(l); std::cout << abc[0] << std::endl; abc[0] = 3; std::cout << abc[0] << std::endl; return (0); } Array.tpp #ifndef ARRAY_TPP # define ARRAY_TPP # include "Array.hpp" template<class T> class Array { private: int size_; T *array_; public: Array() : size_(0), array_(new T[size_]) {}; Array(int n) : size_(n), array_(new T[size_]) {}; Array(Array const& src) : size_(src.size()), array_(new T[src.size()]) { for (int i = 0; i < src.size(); ++i) { array_[i] = src[i]; } }; Array& operator=(Array const& copy) { size_ = copy.size(); delete[] array_; array_ = new T[size_]; for (int i = 0; i < size_; i++) array_[i] = copy[i]; return (*this); } T& operator[](int n) const { if (n < 0 || n >= size_) throw std::out_of_range("out of range"); return (array_[n]); } int size(void) const { return (size_); }; void setValue(T value, int n) { if (n < 0 || n >= size_) throw std::out_of_range("out of range"); array_[n] = value; } ~Array() { delete[] array_; }; }; #endif
The issue is this: T& operator[](int n) const { if (n < 0 || n >= size_) throw std::out_of_range("out of range"); return (array_[n]); } Because this is declared to be a const method, it can be called on a const Array. Though, it returns a non-const reference to the element. Because Array stores the elements via a T *, only that pointer is const in a const Array while modifiying the elements via that pointer is "fine". You need two overloads of operator[]: T& operator[](int n); const T& operator[](int n) const;
74,098,047
74,098,601
Send parameters with dynamically generated QComboBox
I want to insert a QComboBox inside a QTableWidget. When I change the Index of the CB I'll call a methode to change the status in the sqlite table. But for this, I need do pass two parameters to the methode. The ID(First element of the row), and the current index of the CB. I generate the QTableWidget like that: ... for(int i = 0; i < dbModel->rowCount();i++){ row = dbModel->record(i); ui->tW_Services->setItem(i,0,new QTableWidgetItem(row.field(0).value().toString())); ui->tW_Services->setItem(i,1,new QTableWidgetItem(row.field(1).value().toString())); ui->tW_Services->setItem(i,2,new QTableWidgetItem(row.field(2).value().toString())); ui->tW_Services->setItem(i,3,new QTableWidgetItem(row.field(3).value().toString())); ui->tW_Services->setItem(i,4,new QTableWidgetItem(row.field(4).value().toString() + "€")); ui->tW_Services->setItem(i,5,new QTableWidgetItem(row.field(5).value().toString() + "€")); //ui->tW_Services->setItem(i,6,new QTableWidgetItem(row.field(6).value().toString())); QComboBox* combo = new QComboBox(); combo->addItem("open"); combo->addItem("paid"); if(row.field(6).value().toString() != "paid") combo->setCurrentIndex(0); else combo->setCurrentIndex(1); connect(combo, SIGNAL(currentIndexChanged(int)), this, SLOT(onComboChanged(int))); ui->tW_Services->setCellWidget(i,6,combo); } ... and the slot looks like that: void MainWindow::onComboChanged(int ID) { qDebug() << "ID:" << QString::number(ID); } But when I try to create the method with 2 args: void MainWindow::onComboChanged(int ID,int index) { qDebug() << "ID:" << QString::number(ID); } and attach a second parameter and calling the slot like: connect(combo, SIGNAL(currentIndexChanged(int)), this, SLOT(onComboChanged(row.field(0).value().toInt(),int))); I get: qt.core.qobject.connect: QObject::connect: No such slot MainWindow::onComboChanged(row.field(0).value().toInt(),int) A minimal reproducible example: There's just a single pushbutton and a qtablewidget mainwindow.h: #ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> QT_BEGIN_NAMESPACE namespace Ui { class MainWindow; } QT_END_NAMESPACE class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(QWidget *parent = nullptr); ~MainWindow(); private slots: void on_pushButton_clicked(); void onComboChanged(int ID, int index); void onComboChanged2(int index); private: Ui::MainWindow *ui; }; #endif // MAINWINDOW_H mainwindow.cpp: #include "mainwindow.h" #include "ui_mainwindow.h" #include <QComboBox> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) , ui(new Ui::MainWindow) { ui->setupUi(this); } MainWindow::~MainWindow() { delete ui; } void MainWindow::on_pushButton_clicked() { ui->tableWidget->setColumnCount(4); ui->tableWidget->setRowCount(3); for(int i = 0; i < 3;i++){ ui->tableWidget->setItem(i,0,new QTableWidgetItem(QString::number(i))); ui->tableWidget->setItem(i,1,new QTableWidgetItem("Test")); ui->tableWidget->setItem(i,2,new QTableWidgetItem("Test 2")); QComboBox* combo = new QComboBox(); combo->addItem("open"); combo->addItem("paid"); combo->setCurrentIndex(0); int j = i+1; //NOT WORKING //connect(combo, SIGNAL(currentIndexChanged(int)),this, // [=](int index) {this->onComboChanged(j, index);}); //WORKING //connect(combo, SIGNAL(currentIndexChanged(int)),SLOT(onComboChanged2(int))); ui->tableWidget->setCellWidget(i,3,combo); } } void MainWindow::onComboChanged(int ID, int index) { qDebug() << "ID: " << ID << "index: "<< index; } void MainWindow::onComboChanged2(int index) { qDebug() << "ID: " << index; }
Since currentIndexChanged only has one parameter, your slot cannot capture more than that. But, since the row ID does not change on emission, you can wrap onComboChanged into a lambda as shown here, which captures the row by copy: connect(combo, &QComboBox::currentIndexChanged, this, [=](int index) {this->onComboChanged(i, index);}); Since your code is not a minimal reproducible example, I could not test this. Let me know, if it doesn't work.
74,098,207
74,098,567
Pass ownership of an object into method of the same object?
I came across come C++ code similar to the following (more or less minimal) example. Please consider the marked method call in the function on the bottom: #include <memory> static unsigned returnValue = 5; void setReturnValue(unsigned u) { returnValue = u; } class MyObject { public: MyObject(unsigned uIN) : u(uIN) {} ~MyObject() { u = 42; } void method(std::unique_ptr<MyObject> uniqPtrToObject) { // Do something fancy with this unique pointer now, // which will consume the object and its data setReturnValue(uniqPtrToObject->getValue()); } unsigned getValue() { return u; } private: unsigned u; // Some relevant object data }; std::unique_ptr<MyObject> GetUniqToObject(unsigned u) { // Get the object in a fancy way. For now, assume it has just been constructed. return std::make_unique<MyObject>(u); } int main() { std::unique_ptr<MyObject> uniqPtrToObject = GetUniqToObject(0); // =================================================== // Oops! uniqPtrToObject->method(std::move(uniqPtrToObject)); // =================================================== return returnValue; } It looks really strange to move away an object while calling one of its methods. I already tried my example on https://godbolt.org (x64-86 gcc 12.2), and the program returned 0 as it "should". Just some fortunate coincidence? I still wonder: Is this valid C++ syntax? If so, is it portable? If so, is it moral? As I haven't found a good resource where to start research on this situation, I hope you have some advice where to start reading or how to decide this situation easily.
Since you tagged this question C++14, that means we now have to engage with the question of which expression resolves first: the uniqPtrToObject-> one or the initialization of the function parameter? The answer is... it is indeterminate. Neither is sequenced before the other in C++14. The -> is sequenced before the function call and its parameter evaluations in C++17, but this was an explicit change. That means that in C++14, your code's behavior is effectively undefined. If the initialization of the unique_ptr parameter happens before evaluating the -> expression, then uniqPtrToObject will have been moved from by the time -> has been evaluated. Thus, -> gets a nullptr and you access the state of a nullptr. Now, there is some evaluation order. But you don't know what it is, and compilers aren't required to tell you or even be consistent from one execution to the next. So it is unreliable. So let's assume we're talking about C++17. That makes your code well-defined, since it ensures that uniqPtrToObject-> gets evaluated first. However, even if your code "works", it is almost certainly useless within the context of this example. The reason being that you passed uniqPtrToObject by value. That means method() will destroy the unique_ptr, which in turn destroys the object it owns. So if the object stored some data internally, that data is now lost. Whatever modifications were done by this object are no longer accessible, unless it was stored in state outside of the ownership reach of the object. So even on C++ versions where this has consistently-defined behavior, it's not a good idea to actually do.
74,098,791
74,138,899
Soap getProfiles returns error if device codec is set on H.265
I Generated proxy with gSOAP 2.8.123E. Using message included in MediaBindingProxy, I try to retrieve the profile list on a remote Device with GetProfiles message. If I set the device codec on H.264 everything is fine, but when codec is H.265 I retrieve an error in soap response (sniffing with wireshark I notice that the H.265 profile is properly returned). bool soap_OK = false; MediaBindingProxy * media; AddUsernameTokenDigest(media, NULL, GetUser(), GetPwd(), deltaT); //authentication int ret_value = media->GetProfiles(&GetProfiles, GetProfilesResponse); if (ret_value == SOAP_OK) soap_OK = true; //returns true id H.264, with H.265 returns false Could you help me to fix that? if you need further information please ask in comment.
Reading documentation on Onvif profile T, H.265 is enabled in "http://www.onvif.org/ver20/media/wsdl" and not in "http://www.onvif.org/ver10/media/wsdl". This solve the problem.
74,098,960
74,099,124
How can I avoid memory leaks coming from std::list and std::vector
I keep fighting memory leaks on a project coded by a former colleague. Valgrind doesn't seem to like std::vector and std::list resize. For example, if I take this method: void BaseImage::setImageSize(unsigned short width, unsigned short height, unsigned short nbBytePerPixel, const boost::posix_time::ptime& timestamp) { m_timestamp = timestamp; bool change = m_width!=width || m_height!=height || m_bytesByPixel!=nbBytePerPixel; if(change) { m_width = width; m_height = height; m_bytesByPixel = nbBytePerPixel; m_stride = m_width * m_bytesByPixel; if( m_bufferSize < (m_width * m_height * m_bytesByPixel) + m_headerSize) { m_bufferSize = m_width * m_height * m_bytesByPixel; if (m_data.size()!=(m_headerSize + m_bufferSize)) m_data.resize(m_headerSize + m_bufferSize); } } } With: boost::posix_time::ptime m_timestamp; unsigned short m_width; unsigned short m_height; unsigned short m_bytesByPixel; unsigned int m_stride; unsigned int m_bufferSize; unsigned short m_headerSize; std::vector<unsigned char> m_data; I get the following leak in my valgrind logfile: ==10093== 614,412 bytes in 1 blocks are possibly lost in loss record 10,043 of 10,050 ==10093== at 0x4C337B3: operator new(unsigned long) (vg_replace_malloc.c:422) ==10093== by 0x1B9C91: __gnu_cxx::new_allocator<unsigned char>::allocate(unsigned long, void const*) (new_allocator.h:111) ==10093== by 0x1B9ACF: std::allocator_traits<std::allocator<unsigned char> >::allocate(std::allocator<unsigned char>&, unsigned long) (alloc_traits.h:436) ==10093== by 0x1B991D: std::_Vector_base<unsigned char, std::allocator<unsigned char> >::_M_allocate(unsigned long) (stl_vector.h:172) ==10093== by 0x1B934B: std::vector<unsigned char, std::allocator<unsigned char> >::_M_default_append(unsigned long) (vector.tcc:571) ==10093== by 0x1B8E9C: std::vector<unsigned char, std::allocator<unsigned char> >::resize(unsigned long) (stl_vector.h:692) ==10093== by 0x1B716C: xawcore::BaseImage::setImageSize(unsigned short, unsigned short, unsigned short, boost::posix_time::ptime const&) (baseimage.cpp:262) ==10093== by 0x1B6FBD: xawcore::BaseImage::setImageSize(unsigned short, unsigned short, xawcore::PixelType, boost::posix_time::ptime const&) (baseimage.cpp:241) ==10093== by 0x1B6F1E: xawcore::BaseImage::setImageSize(unsigned short, unsigned short, xawcore::PixelType, xawcore::StreamType, boost::posix_time::ptime const&) (baseimage.cpp:229) ==10093== by 0x1B6ECE: xawcore::BaseImage::setImageSize(unsigned short, unsigned short, xawcore::PixelType, xawcore::StreamType, bool, boost::posix_time::ptime const&) (baseimage.cpp:223) ==10093== by 0x21112D: xawcore::OpenNI2Device::acquisition(bool) (openni2device.cpp:314) ==10093== by 0x218219: xawcore::OnlineStream::acquisitionThread(bool) [clone ._omp_fn.0] (onlinestream.cpp:127) I also have a similar error when resize is used on a std::list. Is it a false positive? If not, should I use something else than resize or do some steps before using it?
Valgrind does not tell you that resize did something funny. It tells you that you forgot to deallocate some memory, and gives you an idea on who allocated them, so you can find the responsible to free them. So who should free them? Ah, that would be the vector. And who should free the vector? Ah, that would be your object. And who should free your object? That, only you can tell.
74,100,332
74,107,144
OpenMP parallel for does not speed up array sum code
I'm trying to test the speed up of OpenMP on an array sum program. The elements are generated using random generator to avoid optimization. The length of array is also set large enough to indicate the performance difference. This program is built using g++ -fopenmp -g -O0 -o main main.cpp, -g -O0 are used to avoid optimization. However OpenMP parallel for code is significant slower than sequential code. Test result: Your thread count is: 12 Filling arrays filling time:66718888 Now running omp code 2thread omp time:11154095 result: 4294903886 Now running omp code 4thread omp time:10832414 result: 4294903886 Now running omp code 6thread omp time:11165054 result: 4294903886 Now running sequential code sequential time: 3525371 result: 4294903886 #include <iostream> #include <stdio.h> #include <omp.h> #include <ctime> #include <random> using namespace std; long long llsum(char *vec, size_t size, int threadCount) { long long result = 0; size_t i; #pragma omp parallel for num_threads(threadCount) reduction(+: result) schedule(guided) for (i = 0; i < size; ++i) { result += vec[i]; } return result; } int main(int argc, char **argv) { int threadCount = 12; omp_set_num_threads(threadCount); cout << "Your thread count is: " << threadCount << endl; const size_t TEST_SIZE = 8000000000; char *testArray = new char[TEST_SIZE]; std::mt19937 rng; rng.seed(std::random_device()()); std::uniform_int_distribution<std::mt19937::result_type> dist6(0, 4); cout << "Filling arrays\n"; auto fillingStartTime = clock(); for (int i = 0; i < TEST_SIZE; ++i) { testArray[i] = dist6(rng); } auto fillingEndTime = clock(); auto fillingTime = fillingEndTime - fillingStartTime; cout << "filling time:" << fillingTime << endl; // test omp time for (int i = 1; i <= 3; ++i) { cout << "Now running omp code\n"; auto ompStartTime = clock(); auto ompResult = llsum(testArray, TEST_SIZE, i * 2); auto ompEndTime = clock(); auto ompTime = ompEndTime - ompStartTime; cout << i * 2 << "thread omp time:" << ompTime << endl << "result: " << ompResult << endl; } // test sequential addition time cout << "Now running sequential code\n"; auto seqStartTime = clock(); long long expectedResult = 0; for (int i = 0; i < TEST_SIZE; ++i) { expectedResult += testArray[i]; } auto seqEndTime = clock(); auto seqTime = seqEndTime - seqStartTime; cout << "sequential time: " << seqTime << endl << "result: " << expectedResult << endl; delete[]testArray; return 0; }
As pointed out by @High Performance Mark, I should use omp_get_wtime() instead of clock(). clock() is 'active processor time', not 'elapsed time. See OpenMP time and clock() give two different results https://en.cppreference.com/w/c/chrono/clock After using omp_get_wtime(), and fixing the int i to size_t i, the result is more meaningful: Your thread count is: 12 Filling arrays filling time:267.038 Now running omp code 2thread omp time:26.1421 result: 15999820788 Now running omp code 4thread omp time:7.16911 result: 15999820788 Now running omp code 6thread omp time:5.66505 result: 15999820788 Now running sequential code sequential time: 30.4056 result: 15999820788
74,100,507
74,100,664
C++ Expression: Vector subscript out of range
I recently started learning c++ and I'm trying to make a tic-tac-toe game. I'm using a vector for the board and modifying the board once per player turn. The board looks like this: std::vector<char> board = { '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', }; Here is the function modifying the board: int player_turn(std::vector<char> board) { int guess; std::cout << "Please enter field 1-9: \n"; std::cin >> guess; if (guess < 10 && guess > 0 && board[guess-1] == '-') return(guess); else { std::cout << "Invalid input! Try again\n"; player_turn(board); } } This is how I'm calling the function in my main file: board[player_turn(board) - 1] = 'O'; If I run the program and only enter valid guesses that don't trigger the recursion it works without issues. However if I try entering an invalid input that doesn't trigger the if block, as long as I enter invalid inputs the else block triggers and the function runs again. But if I enter an invalid input, and then a valid input I get the error Expression: vector subscript out of range. As far as I can tell that error comes up when I try to access an index in the vector that doesn't exist. What I don't understand is why that is happening. I can't figure out what modifies the vector after an invalid input when it shouldn't change at all until a valid input is there. Thanks in advance.
You're experiencing undefined behavior since your function doesn't return a value in each branch. int player_turn(std::vector<char> board) { int guess; std::cout << "Please enter field 1-9: \n"; std::cin >> guess; if (guess < 10 && guess > 0 && board[guess-1] == '-') return(guess); else { std::cout << "Invalid input! Try again\n"; return player_turn(board); // ^^^^^^ } } There are many ways you can avoid such mistakes. First, you could enable warnings. Using GCC or Clang, add the -Werror=return-type compiler flag to make such code not compile. Using MSVC, such code will not compile by default. You can also mark your function as nodiscard: [[nodiscard]] int player_turn(std::vector<char> board) { // ... } This will make the compiler emit a warning if you call the function but ignore the result.
74,101,066
74,105,309
Getting co_await with boost::process::async_system working
Like the title says, I want to co_await for a process spawned with boost::process::async_system. So I'm doing something like this: Example on Coliru namespace bp = boost::process; bp::async_pipe ap(io_); // Create the child process object with our parameters and a redirected stdout co_await bp::async_system(io_, boost::asio::use_awaitable, bp::search_path(command), bp::start_dir(cwd), bp::args(args), bp::std_out > ap); But I'm getting a very unhelpful error-message. My assumption now is, that async_system is not compatible with co_await. Is there another (maybe generic) way to integrate 3rd party async mechanisms in boost::asio::awaitable? (I feel a bit lost in this whole boost::asio / c++ coro topic. Google is not very helpful and the boost doc a bit too minimalistic for me.)
I'd mold the code a bit for style: http://coliru.stacked-crooked.com/a/33667a7d106de0e7 The Real Problem Now with the above, there's is still an error inside my_coro when you try to uncomment the async_system call. Instead of reading the message, I looked at the code, figured that it should have worked, and looked at the implementation: template<typename ExitHandler, typename ...Args> inline BOOST_ASIO_INITFN_RESULT_TYPE(ExitHandler, void (boost::system::error_code, int)) async_system(boost::asio::io_context & ios, ExitHandler && exit_handler, Args && ...args) { detail::async_system_handler<ExitHandler> async_h{ios, std::forward<ExitHandler>(exit_handler)}; typedef typename ::boost::process::detail::has_error_handler<boost::fusion::tuple<Args...>>::type has_err_handling; static_assert(!has_err_handling::value, "async_system cannot have custom error handling"); child(ios, std::forward<Args>(args)..., async_h ).detach(); return async_h.get_result(); } After looking at the implementation, I figured that /usr/local/include/boost/asio/async_result.hpp:651:9: error: no type named 'completion_handler_type' in 'class boost::asio::async_result<boost::asio::use_awaitable_t<>, void(boost::system::error_code, int)>' indicates that Boost Process has not been updated to support newer async_result protocol, which instead of completion_handler_type appears to use the initiate member function. This gives the async_result implementation more options, which are probably required for use_awaitable_t tokens. I'd raise an issue at the library. Note that current develop branch has code underway that does seem to correctly support use_awaitable (e.v. boost/process/v2/popen.hpp)
74,101,362
74,105,362
Convert a streambuf to const_buffer
How do I "consume" a streambuf and thereby convert it to a const_buffer? Example: const_buffer read(boost::shared_ptr<tcp::socket> sock) { boost::system::error_code error; // getting response from server boost::asio::streambuf receive_buffer; boost::asio::read(*sock, receive_buffer, boost::asio::transfer_all(), error); if( error && error != boost::asio::error::eof ) { cout << "receive failed: " << error.message() << endl; exit(1); } else { // I want something like return const_buffer(receive_buffer); } } Being able to convert it to a mutable buffer is also ok.
const_buffer is not an owning data structure. Logically, you cannot consume the data and still have a const_buffer referencing it. You should probably use a container like std::string or std::vector: return std::string(buffers_begin(receive_buffer.data()), buffers_end(receive_buffer.data())); // or return std::vector<uint8_t>(buffers_begin(receive_buffer.data()), buffers_end(receive_buffer.data())); That said, since you're not interested in the dynamic streambuf, why use it? auto read(tcp::socket& sock) { std::string result; // std::vector<uint8_t> result; boost::system::error_code ec; asio::read(sock, asio::dynamic_buffer(result), ec); if (ec && ec != asio::error::eof) { std::cout << "receive failed: " << ec.message() << std::endl; exit(1); } return result; } That has the same effect but more efficiently. PS If you ever need a const_buffer referencing the chosen container type (std::string or std::vector), a simple asio::buffer(s) will do precisely that.
74,101,443
74,101,473
Wrong placement in 2d vector
I'm trying to print a full closed maze (where the user inputs width and height), but when I print the maze the "|" walls are not placed correct. Why is this, because the parameters are set. Also the right amount of "|" are placed but at wrong positions int vectorLength = (userRows * 2) + 1; int vectorWidth = (userColloms * 4) + 1; std::vector<std::vector<std::string>> maze(vectorWidth, std::vector<std::string>(vectorLength, "")); for (unsigned int i = 0; i < vectorLength; i++) { int testj = 0; for (unsigned int j = 0; j < vectorWidth; j++) { if (i % 2 == 0){ if (j % 4 == 0) { maze.at(j).at(i) = "+"; } else { maze.at(j).at(i) = "-"; } } if (i % 2 != 0){ if (j % 4 == 0) { maze.at(j).at(i) = "|"; } } } } The output for input 3 3 : +---+---+---+ |||| +---+---+---+ |||| +---+---+---+ |||| +---+---+---+ Program ended with exit code: 0
It looks like your code works by replacing characters in your maze vector. Since your vector is initialized all to empty strings, there is nothing between each "|" to give space. You should either initialize your vector to be full of spaces " " or find another way to pad the space between each bar.
74,101,498
74,102,669
CPython C/C++ extension: Dealloc never called
Initial situation: I have a Python C extension module which defines a init() method which creates and returns a new Python object. I followed the approach of heaptypes.c in the official python sources. My source code (my_module.cpp) is almost a 1:1 copy of the example in the Python sources : typedef struct { PyObject_HEAD int value; } HeapCTypeObject; static int heapctype_init(PyObject *self, PyObject *args, PyObject *kwargs) { std::cout << "Init called" << std::endl; ((HeapCTypeObject *)self)->value = 10; return 0; } static struct PyMemberDef heapctype_members[] = { {"value", T_INT, offsetof(HeapCTypeObject, value)}, {NULL} /* Sentinel */ }; static void heapctype_dealloc(HeapCTypeObject *self) { std::cout << "dealloc called" << std::endl; PyTypeObject *tp = Py_TYPE(self); PyObject_Free(self); Py_DECREF(tp); } PyDoc_STRVAR(heapctype__doc__, "A heap type without GC, but with overridden dealloc.\n\n" "The 'value' attribute is set to 10 in __init__."); static PyType_Slot HeapCType_slots[] = { {Py_tp_init, (void*)heapctype_init}, {Py_tp_members, heapctype_members}, {Py_tp_dealloc, (void*)heapctype_dealloc}, {Py_tp_doc, (char*)heapctype__doc__}, {0, 0}, }; static PyType_Spec HeapCType_spec = { "MyModule.HeapCType", sizeof(HeapCTypeObject), 0, Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, HeapCType_slots }; static PyObject* init(PyObject *self, PyObject *args){ PyObject *HeapCType = PyType_FromSpec(&HeapCType_spec); return HeapCType; } PyMethodDef method_table[] = { {"init", (PyCFunction) init, METH_NOARGS, "Construct create new PyObject"}, {NULL, NULL, 0, NULL} // Sentinel value ending the table }; // A struct contains the definition of a module PyModuleDef mymod_module = { PyModuleDef_HEAD_INIT, "MyModule", // Module name "This is MyModule's docstring", -1, // Optional size of the module state memory method_table, NULL, // Optional slot definitions NULL, // Optional traversal function NULL, // Optional clear function NULL // Optional module deallocation function }; PyMODINIT_FUNC PyInit_MyModule(void) { return PyModule_Create(&mymod_module); } Importing the module und creating a new instance works fine: import MyModule x = MyModule.init() However, when I delete the instance, the heapctype_dealloc(HeapCTypeObject *self) gets never called: import gc del x gc.collect() Even when I quit the interpreter, the deallocation methods does not get called and I don't know why. As my plan is to combine this approach witch a C++ class allocated on the heap, I would get a rock-solid memory leak if the deallocation method won't get called. The behaviour can be reproduces with the following steps: git clone https://github.com/hANSIc99/PythonCppExtension/tree/stackoverflow cd PythonCppExtension cmake -B build cmake --build buil source init.sh python3 -i main.py I also observed that right after the call to to PyType_FromSpec(...), the newly created class has already an reference count of 4. What I'm doing wrong here? How can I ensure that the deallocation methods is called when the instance is destroyed? Thanks for your help!
You are using the API incorrectly. PyType_FromSpec returns a TYPE, not an Object instance (it is not the same as PyObject_New). So it will never call init (the constructor) of said type. You are doing: x = MyModule.init(). x is actually a HeapCTypeObject TYPE. You haven't constructed an instance of that type yet. If you print(x), you'd see <class 'MyModule.HeapCType'> To do so, you need to do: import MyModule HeapCTypeObject = MyModule.init() x = HeapCTypeObject() If you then print(x) you'd see <MyModule.HeapCType object at 0x10702bb70> Now it will call your constructor and destructor correctly. This is useful for creating dynamic types. But if you already know what your type looks like, why not just create it directly and expose it via PyModule_AddObject? IE: #include <Python.h> #include "methodobject.h" #include "object.h" #include "pyport.h" #include <structmember.h> #include <cstdio> typedef struct { PyObject_HEAD int value; } HeapCTypeObject; static int heapctype_init(PyObject *self, PyObject *args, PyObject *kwargs) { fprintf(stderr, "INIT CALLED\n"); ((HeapCTypeObject *)self)->value = 10; return 0; } static struct PyMemberDef heapctype_members[] = { {"value", T_INT, offsetof(HeapCTypeObject, value)}, {NULL} /* Sentinel */ }; static void heapctype_dealloc(HeapCTypeObject *self) { fprintf(stderr, "DEALLOC CALLED\n"); PyTypeObject *tp = Py_TYPE(self); PyObject_Free(self); Py_DECREF(tp); } PyDoc_STRVAR(heapctype__doc__, "A heap type without GC, but with overridden dealloc.\n\n" "The 'value' attribute is set to 10 in __init__."); static PyType_Slot HeapCType_slots[] = { {Py_tp_init, (void*)heapctype_init}, {Py_tp_members, heapctype_members}, {Py_tp_dealloc, (void*)heapctype_dealloc}, {Py_tp_doc, (char*)heapctype__doc__}, {Py_tp_base, (void *)&PyType_Type}, {0, NULL}, }; static PyTypeObject HeapCType = { PyVarObject_HEAD_INIT(NULL, 0) .tp_name = "HeapCTypeObject", .tp_doc = PyDoc_STR("Custom objects"), .tp_basicsize = sizeof(HeapCTypeObject), .tp_itemsize = 0, .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE, .tp_new = nullptr, .tp_init = (initproc) heapctype_init, .tp_dealloc = (destructor) heapctype_dealloc, .tp_members = heapctype_members, .tp_methods = nullptr, }; PyMethodDef method_table[] = { {NULL, NULL, 0, NULL} // Sentinel value ending the table }; // A struct contains the definition of a module PyModuleDef mymod_module = { PyModuleDef_HEAD_INIT, "MyModule", // Module name "This is MyModule's docstring", -1, // Optional size of the module state memory method_table, NULL, // Optional slot definitions NULL, // Optional traversal function NULL, // Optional clear function NULL // Optional module deallocation function }; PyMODINIT_FUNC PyInit_MyModule(void) { if (PyType_Ready(&HeapCType) < 0) return NULL; PyObject* module = PyModule_Create(&mymod_module); Py_INCREF(&HeapCType); if (PyModule_AddObject(module, "HeapCTypeObject", (PyObject *) &HeapCType) < 0) { Py_DECREF(&HeapCType); Py_DECREF(module); return NULL; } return module; } Then in Python you'd do: from MyModule import HeapCTypeObject x = HeapCTypeObject() which is much clearer.
74,101,544
74,102,123
Must difference_type be comparable?
The requirements for random access iterators are found here. On this page, you will see that for any two RandIts, a and b, a<b and a-b are both legal c++. a-b returns a difference_type. In my code, I want to compute a<b, but instead of comparing a and b, I want to compare a-first and b-first. This requires two things: difference_types are comparable. (a-first < b-first) == (a < b). It would be easy to implement comparison of difference_types as satisfying (2), but I can't tell if this is required by the standard. Do (1) and (2) hold?
The standard requires iterator_traits<It>::difference_type to be a "signed integer type" (or void). This statement is to be taken literally. [basic.fundamental]/1 defines a number of types which are "integer types" and a subset of them to be "signed integer types". These are the only "signed integer types" in C++. You may create types which act like "signed integer types," but the standard clearly defines a specific set of functional types which fit this term. And your user-defined types aren't them. So it's not your choice whether difference_type is "comparable" or not; all integer types are comparable because that's how C++ defines them.
74,101,568
74,102,013
Memory usage of a vector of struct with an int and a string
What is the expected memory usage of a vector of a struct, that contains a string (let's say on average 5 bytes), an int (4 bytes) and a double (8 bytes). Would each entry just take 17 bytes or are there other things to consider? struct Entry { int entry1; string myString; // on average 5 characters double value; } vector<Entry> dataframe
You're going to use at least sizeof(std::vector<Entry>) + N * sizeof(Entry) bytes, and short string optimization means that if all of your strings are short you'll probably use exactly that much. How much memory that is will depend on your compiler, standard library implementation, and architecture. Assuming you're compiling for x86_64, sizeof(Entry) will likely be either 40 or 48 bytes (MSCRT and libstdc++ have 32 byte std::strings, libc++ uses 24 byte std::strings). sizeof(std::vector<Entry>) is likely 24 bytes. That brings total memory usage up to a likely 24 + N * 48 bytes. If your strings are longer than about 15 characters then std::string will have to store the actual character data in an external allocation. That can add an arbitrary extra amount of memory usage. Note that this is just the memory directly used to store your objects. The memory allocator may allocate memory from the system in larger chunks, and there's also some overhead used for tracking what memory is allocated and what is available.
74,101,708
74,101,780
Simplifying the Makefile
I use this Makefile to build a small C++ application: BIN_CPP=Main CPP=g++ INCLUDES_APR=/usr/local/apr/include/apr-1 LIB_SRC = $(wildcard My*.cpp) LIB_OBJ = $(LIB_SRC:.cpp=.o) RM=rm all: Main MyClass.o: MyClass.cpp $(CPP) -I$(INCLUDES_APR) -c $< -o $@ MyModel.o: MyModel.cpp $(CPP) -I$(INCLUDES_APR) -c $< -o $@ libMyLibrary.so: $(LIB_OBJ) $(CPP) -fPIC -shared -o $@ $^ Main.o: Main.cpp $(CPP) -o $@ -c $^ -I$(INCLUDES_APR) Main: libMyLibrary.so Main.o $(CPP) $^ -o $@ -L/usr/local/apr/lib -L. -lapr-1 -lMyLibrary .PHONY: clean clean: $(RM) -f *.o *.so $(BIN_CPP) When I remove then first two targets and extend the libMyLibrary.so one, it fails: # MyClass.o: MyClass.cpp # $(CPP) -I$(INCLUDES_APR) -c $< -o $@ # MyModel.o: MyModel.cpp # $(CPP) -I$(INCLUDES_APR) -c $< -o $@ libMyLibrary.so: $(LIB_OBJ) $(CPP) -fPIC -shared -o $@ $^ -I$(INCLUDES_APR) and the error message is this: g++ -c -o MyClass.o MyClass.cpp In file included from MyClass.cpp:1: MyClass.hpp:3:10: fatal error: apr_general.h: No such file or directory 3 | #include <apr_general.h> | ^~~~~~~~~~~~~~~ compilation terminated. make: *** [<builtin>: MyClass.o] Error 1 The -I$(INCLUDES_APR) is missing from the automake output. What is wrong with this build file?
By removing the explicit rules, you are relying on GNU make's built-in rules to compile your files, which is good. But GNU make's built-in rules can't possibly know about your local variable INCLUDES_APR, so when it compiles the source files that variable is not used. You should add the -I flag to the standard variable CPPFLAGS (the "CPP" here stands for "C preprocessor", not "C++"), which is what make uses to compile in its built-in rules. Example: BIN_CPP=Main CPP=g++ INCLUDES_APR=/usr/local/apr/include/apr-1 CPPFLAGS=-I$(INCLUDES_APR) LIB_SRC = $(wildcard My*.cpp) LIB_OBJ = $(LIB_SRC:.cpp=.o) RM=rm all: Main libMyLibrary.so: $(LIB_OBJ) $(CPP) -fPIC -shared -o $@ $^ Main: Main.o libMyLibrary.so $(CPP) $< -o $@ -L/usr/local/apr/lib -L. -lapr-1 -lMyLibrary .PHONY: clean clean: $(RM) -f *.o *.so $(BIN_CPP) Possible make output g++ -I/usr/local/apr/include/apr-1 -c -o Main.o Main.cpp g++ -I/usr/local/apr/include/apr-1 -c -o MyClass.o MyClass.cpp g++ -I/usr/local/apr/include/apr-1 -c -o MyModel.o MyModel.cpp g++ -fPIC -shared -o libMyLibrary.so MyClass.o MyModel.o g++ Main.o -o Main -L/usr/local/apr/lib -L. -lapr-1 -lMyLibrary
74,102,221
74,102,375
What does type aliasing through reference (of `signed` to `unsigned`) with `reinterpret_cast` do?
My questions are: As of which version of the standard does the following code become valid (if any)? What is the observable behavior of the program? (In C++20) #include <climits> int main() { int foo = INT_MAX; ++reinterpret_cast<unsigned&> (foo); // foo = static_cast<int> (foo + 1u) return INT_MIN == foo; } Based on the following excerpt I believe this program returns 1. (See: Example on Compiler Explorer). 7.6.1.10 Reinterpret cast [expr.reinterpret.cast] 1 The result of the expression reinterpret_­cast<T>(v) is the result of converting the expression v to type T. If T is an lvalue reference type […] the result is an lvalue; 7 An object pointer can be explicitly converted to an object pointer of a different type. When a prvalue v of object pointer type is converted to the object pointer type “pointer to cv T”, the result is static_­cast<cv T*>(static_­cast<cv void*>(v)). [Note 6: Converting a pointer of type “pointer to T1” that points to an object of type T1 to the type “pointer to T2” (where T2 is an object type and the alignment requirements of T2 are no stricter than those of T1) and back to its original type yields the original pointer value. — end note] 11 A glvalue of type T1, designating an object x, can be cast to the type “reference to T2” if an expression of type “pointer to T1” can be explicitly converted to the type “pointer to T2” using a reinterpret_­cast. The result is that of *reinterpret_­cast<T2 *>(p) where p is a pointer to x of type “pointer to T1”. No temporary is created, no copy is made, and no constructors ([class.ctor] or conversion functions ([class.conv]) are called. Further reading: TL;DR: The answer. 6.8.2.6 [basic.fundamental] 6 A fundamental type specified to have a signed or unsigned integer type as its underlying type has the same object representation, value representation, alignment requirements ([basic.align]), and range of representable values as the underlying type. Further, each value has the same representation in both types. 6.8.1.4 [basic.types.general] 4 The object representation of an object of type T is the sequence of N unsigned char objects taken up by the object of type T, where N equals sizeof(T). The value representation of an object of type T is the set of bits that participate in representing a value of type T. Bits in the object representation that are not part of the value representation are padding bits. For trivially copyable types, the value representation is a set of bits in the object representation that determines a value, which is one discrete element of an implementation-defined set of values.
This has been permitted for all versions prior to C++20 according to the strict aliasing rule: If a program attempts to access the stored value of an object through an lvalue of other than one of the following types the behavior is undefined: ... a type that is the signed or unsigned type corresponding to the dynamic type of the object, C++20 changed the form of the strict aliasing rule, but the signed/unsigned variation remains permissible: If a program attempts to access the stored value of an object through a glvalue whose type is not similar to one of the following types the behavior is undefined: ... a type that is the signed or unsigned type corresponding to the dynamic type of the object Here the dynamic type is signed int, your glvalue has the corresponding unsigned type unsigned int, so the access is allowed. C++20 also made the result well-defined by mandating two's-complement encoding of signed numbers. Previously you would manipulate the bit representation in a well-defined way but there was no particular guarantee on what value came out when read as signed int later.
74,102,290
74,108,719
clang-format and special delimiters
I am using a special raw string delimiter in my code to format doc string, it looks something like R"mydelimiter( some raw string )mydelimiter" Now, clang-format likes to produce the following R "mydelimiter( some raw string ) mydelimiter " which actually introduces a compilation error. I know that I can mark every block in my code with // clang-format on/off but I would like to find a more general solution. Here is what I tried so far: raw string format in my .clang-format RawStringFormats: - Language: Cpp Delimiters: ['mydelimiter'] as well as several versions of regex macro blocks MacroBlockBegin: 'R\"mydelimiter\(' MacroBlockEnd: '\)mydelimiter\",' without any success. I am running clang-format version 14.0.6 and also I am running out of ideas :-/ help!
As pointed out in the GitHub issue opened for this, the problem is in the GNU style option. clang-format relies on the clang parser, but the clang parser may give different results for different versions of the C++ standard. The GNU style option sets the C++ standard used for parsing to C++03, a time where raw string literals did not exist, therefore the parser does not correctly recognize them as such. The standard set by GNU can be overridden in your config by adding Standard: Latest, or just specifying any standard version 11 or higher
74,102,415
74,102,577
Properly handling owner drawn Win32 button hovering
I want to add multiple color themes to my Win32 application, this means that I have to manually handle all the control drawing manually by using the BS_OWNERDRAW style flag. I then handle all the drawing in the WM_DRAWITEM message through the LPDRAWITEMSTRUCT structure stored in the lParam. Here's the problem though, by introducing owner drawing I also have to handle click and hover events, which in and of itself isn't a problem but it becomes one because it turns out that the LPDRAWITEMSTRUCT has no message being sent to indicate whether or not a control is being hovered. The itemState member do have messages like ODS_SELECTED, ODS_FOCUS and so on, but no flag for hovering only. That being said, there does exist a flag named ODS_HOTLIGHT which according to MSDN should do the job, the problem however is that this flag never occurs for buttons, only menu items. I've tried using the SetWindowSubclass function by giving each control it's separate WindowProc callback where you can track the mouse leaving and entering the control. This works, but that also means that I need to transition all drawing commands over to the subclass procedure, which seems rather stupid to me, since the WM_DRAWITEM is intended for custom drawing in the first place. You could always send WM_DRAWITEM manually via SendMessage but that also means that I need to provide an LPDRAWITEMSTRUCT manually which hasn't worked out that great. In essence I do not know what the best approach is to react to these hover events and draw them accordingly, the LPDRAWITEMSTRUCT does not provide such a flag and thus I have no idea what other approach to use. How should I tackle this? The way I'm currently handling the WM_DRAWITEM message (buttons only): case WM_DRAWITEM: { LPDRAWITEMSTRUCT pDIS = (LPDRAWITEMSTRUCT)lParam; HPEN borderPen = CreatePen(PS_INSIDEFRAME, 0, RGB(0, 0, 0)); HGDIOBJ oldPen = SelectObject(pDIS->hDC, borderPen); HGDIOBJ oldBrush; if (pDIS->itemState & ODS_SELECTED) { oldBrush = SelectObject(pDIS->hDC, buttonHoverBrush); } else { oldBrush = SelectObject(pDIS->hDC, buttonDefaultBrush); } // Rounded button RoundRect(pDIS->hDC, pDIS->rcItem.left, pDIS->rcItem.top, pDIS->rcItem.right, pDIS->rcItem.bottom, 5, 5); //Clean up SelectObject(pDIS->hDC, oldPen); SelectObject(pDIS->hDC, oldBrush); DeleteObject(borderPen); // Calculate button dimensions int buttonWidth = pDIS->rcItem.right - pDIS->rcItem.left; int buttonHeight = pDIS->rcItem.bottom - pDIS->rcItem.top; WCHAR staticText[128]; int len = SendMessage(pDIS->hwndItem, WM_GETTEXT, ARRAYSIZE(staticText), (LPARAM)staticText); HFONT buttonFont = (HFONT)SendMessage(pDIS->hwndItem, WM_GETFONT, 0, 0); SIZE buttonDim; HFONT oldFont = (HFONT)SelectObject(pDIS->hDC, buttonFont); GetTextExtentPoint32(pDIS->hDC, staticText, len, &buttonDim); SetTextColor(pDIS->hDC, RGB(255, 255, 255)); SetBkMode(pDIS->hDC, TRANSPARENT); TextOut(pDIS->hDC, buttonWidth / 2 - buttonDim.cx / 2, buttonHeight / 2 - buttonDim.cy / 2, staticText, len); wasHandled = TRUE; result = TRUE; break; } The code listed above creates a button with a given background color and centers text within it. It also changes color to the hover rush when clicked. What I want to happen is that the button changes its color immediately upon hover and not upon click. Thank you in advance!
I've tried using the SetWindowSubclass function by giving each control it's separate WindowProc callback where you can track the mouse leaving and entering the control. This works, but that also means that I need to transition all drawing commands over to the subclass procedure, which seems rather stupid to me, since the WM_DRAWITEM is intended for custom drawing in the first place. Unfortunately, that is precisely what you will likely need to do. For instance, you can have the button's subclass procedure handle the WM_MOUSEMOVE message to detect when the mouse is over the button, and handle the WM_MOUSELEAVE message to detect when the mouse moves out of the button. The message handler can use WM_MOUSEMOVE to call TrackMouseEvent() to trigger WM_MOUSELEAVE and WM_MOUSEHOVER messages. It can then use WM_MOUSEHOVER to set a flag and invalidate the button to trigger a repaint, and it can use WM_MOUSELEAVE to clear the flag and invalidate the button to trigger a repaint. Inside the button's normal draw handler (which DOES NOT need to be moved to the subclass procedure. BTW), if the flag is set then draw the button as hovered, otherwise draw it as non-hovered. The only gotcha with this approach is if you have multiple buttons then you will need multiple flags, one per button. But you can use (Get|Set)WindowLongPtr(GWL_USERDATA) or (Get|Set)Prop() to store/retrieve each button's flag inside/from the button's HWND directly Or, you can just maintain your own std::map (or other lookup table) of HWND-to-flag associations. Another option would be to have the subclass procedure use the WM_MOUSE(MOVE|HOVER|LEAVE) messages to send simulated WM_DRAWITEM messages to the button, specifying/omitting the ODS_HOTLIGHT style as needed so the drawing code can look for that style. You might need the subclass procedure to intercept WM_PAINT messages to make that work, though. Not sure about that. Otherwise, you could simply have your WM_DRAWITEM handler grab the mouse's current coordinates and see if they fall within the button's client area, and then draw accordingly.
74,102,714
74,140,838
what cpp function in firefox gets invoked when javascript invokes clipboard.getData()?
What C++ function is invoked in Firefox source code when Javascript invokes clipboard.getData() ? My guess is line 57 in MessageEvent::getData But when I put a printf statement in there, it never gets hit. Does anyone know which C++ function gets called in Firefox source when Javascript invokes clipboard.getData() ?
DataTransfer::GetData is invoked.
74,103,004
74,157,547
How Unreal Engine implements UPROPERTY macro?
I'd like to implement something like UPROPERTY() macro in my project, but I cannot find any references of what it actually is. I mean, there're are tutorials on how this macro works, but these are just use cases. How does the compiler know that UPROPERTY() references the variable under it? example: UPROPERTY(EditAnywhere) int x = 0; I know that unreal is open source, but its codebase is huge.
UPROPERTY is not a real C++ macro. It looks like one, so the compiler accepts it, but it actually is used by the Unreal Header Tool (UHT) to create code that will then be added in the GENERATED_BODY code of your class. The UHT is a parser that just takes all of your code and searches for all those UCLASS, UPROPERTY, UFUNCTION, etc. declarations and then generates the proper code for it that will then be put in the "XXX.generated.h" and "XXX.generated.cpp" files that you include. For example, if you want your variable to be readable via blueprints, a getter logic is created to allow the blueprint logic to call it. So the compiler does not actually know anything about what a UPROPERTY is, because the pre processor removes it entirely due to it not having an actual body. If you want to know how the UHT works in depth, you should look into its code. There you could also modify it to suit your needs, including custom code generation. A side note regarding macros in Unreal: The Slate framework in Unreal actually uses macros to generate a lot of boilerplate code without the Unreal Header Tool. Maybe looking into it will give you some insights. But they are not identical to the power of the code generation done by the UHT.
74,103,156
74,103,407
Sample application with imgui library generate error
I am new in imgui and just installed it with vcpkg and created an application in vs2022 and add these codes: #include <imgui.h> using namespace std; void MySaveFunction() { } int main() { ImGui::Text("Hello, world %d", 123); if (ImGui::Button("Save")) MySaveFunction(); } but when I run this application I get this error: What minimum code do I need to display a window with a button on it? I searched on the IMGUI website but could not find any simple sample that works.
Dear ImGui provided some detailed examples on how to get started. Don't be scared to read the code, which might be long and overwhelming if you are new to it. You basically need to choose a backend, I personally prefer DirectX 11. Then you have to create a window and initialize DirectX. Then create the ImGuiContext - which throws the error for g is nullptr because the context wasn't created, and initialize the backend after that.
74,103,820
74,103,973
Making a class template declared in an outer anonymous namespace a friend
Clang refuses to compile the following code (godbolt) while gcc sees no problem with it. Clang error message is shown below line marked (2): namespace // Overall anonymous namespace is required and cannot be removed. { template <typename T> struct Friend; namespace ns { class Secret { template <typename T> friend struct Friend; // (1) static void foo() {} }; } // namespace ns template <typename T> struct Friend { void bar() { ns::Secret::foo(); // (2) // Error at line (2): // 'foo' is a private member of '(anonymous namespace)::ns::Secret' } }; } // anonymous namespace The reason, I assume, is that line (1) is treated as a declaration of a new class template struct ns::Friend<T> rather than a reference to ::(anonymous namespace)::Friend<T>. The questions are: Who's right -- clang or gcc? If clang is right, then is there a way to make it understand that line (1) doesn't introduce new class template, but refers to existing one?
Yes, you are right that simply friend struct Friend is a declaration of a templated class ::(anonymous namespace)::ns::Friend. Both compilers are right, as when you attempt to use Friend<T>::bar() gcc will complain about access as well (clang just checks a lot earlier than gcc) To specify the class template in the global namespace, you must write that out: template <typename T> friend struct ::Friend; // (1) This works for GCC, but clang seems broken and doesn't find Friend in the global namespace. These two workarounds seem to work: // Make the entire unnamed namespace an inline namespace inline namespace { // ... } // Add an explicit using directive to help clang find Friend in `::` namespace { template<typename T> struct Friend; } using ::Friend; namespace { namespace ns { // ... } }
74,104,224
74,104,272
Since For loops is n Timecomplexity So is it Better To Use Only couts for example in cpp and never use for loops?
in algorithms Complexity For loops is N Time complex Nested For loop Is n2 time complex but cout in cpp or printf in c and cpp is Constant time Complex So its faster so is it Better To use Cout 10 times to print number1to10 since its Actually faster ? or ? (We should use Only for loops when Its really hard to code it for example 1k line of code or something!); like cout<<1; cout<<2; cout<<3; cout<<4; and so on Instead of for(int i=1;i<=10;i++){ cout<<i<<" "; } its a Beginner Question(so sorry if its weird) but it just got into my Head and i literally couldn't find any answer to it And tried to search for it But i found nothing!
If you copy and paste a printout n times then the code still takes O(n) time. Unrolling the loop doesn't change the fact that you've got n printouts. Except now you have O(n) lines of code instead of the O(1) lines of a for loop.
74,104,268
74,104,287
Undefined Behavior in Unions with Standard Layout structs
Take the following code union vec { struct { float x, y, z; }; float data[3]; constexpr vec() : data{} {} }; constexpr vec make_vec(float x, float y, float z) { vec res; res.data[0] = x; res.data[1] = y; res.z = z; return res; } int main() { constexpr vec out = make_vec(0, 1, 2); std::cout << out.z << '\n'; } I make use of constexpr here to determine whether the code is undefined behavior or not, as the undefined behavior will cause a compilation error. §9.2/19: If a standard-layout union contains two or more standard-layout structs that share a common initial sequence, and if the standard-layout union object currently contains one of these standard-layout structs, it is permitted to inspect the common initial part of any of them. From this, I would assume that everything in the code would be defined behavior. Compiling with g++ main.cpp -o out -std=c++17, I get the message error: change of the active member of a union from 'vec::data' to 'vec::<anonymous>'. I thought that to comply with the standard, I might've had to change it to this-- union vec { struct { float x, y, z; }; struct { float data[3]; }; constexpr vec() : data{} {} }; But I get the same error. Is this truly undefined behavior? Is there perhaps another part of the standard that I've missed, or am I simply misinterpreting the standard?
Yes, this is UB. After you write to float data[3]; part of the union, you are not allowed to read the struct { float x, y, z; }; This is as simple as that. that share a common initial sequence Doesn't cover these two, as an array is not the same as a float followed by another float. Important edit The answer above assumed the code was UB as the .x and .y members would not be valid. As @user17732522 points out. It is a bit more subtle than that. .x and .y are returned uninitialized and would have undefined values. But the write to the .z member indeed sets the active member of the union. As such, as long as the calling code only reads the .z member, everything is defined and correct.
74,104,455
74,104,511
Get a vector that is rotated towards a point that is perpendicular to a normal vector
I want to calculate a vector that is perpendicular to a normal vector of a plane, and if you are looking at the plane top down you will see the resulting vector pointing towards a point. Example Image: What I've tried This is the code I've made to try to calculate the vector. It doesn't work not sure what to add to fix it. int sgn(float val) { return (0.0f < val) - (val < 0.0f); } void DetermineVector(Vector3 normalVector, Vector3 hitPosition, Vector3 goalPoint) { float deltaX = goalPoint.X - hitPosition.X; // TO - FROM float deltaY = goalPoint.Y - hitPosition.Y; // TO - FROM float deltaZ = goalPoint.Z - hitPosition.Z; // TO - FROM // Determine the x, z components of the vector. // Basic Pythagorean Theorem float length = sqrt(deltaX * deltaX + deltaZ * deltaZ); float x = deltaX / length; float z = deltaZ / length; // Determine the y component of the vector; // Gets the sign of angle rotation float crossProductSum = -normalVector.X * deltaY + normalVector.Y * deltaX; int sign = sgn(crossProductSum); // Gets the sign -1, 0, and 1 // Use trigonometry to figure out the angle of the normal vector in relation to the UP vector (0, 1, 0) // take that angle and subtract rotate 90 and take that resulting y vector and multiply the sign float angle = acos(normalVector.Y); float y = cos(angle - 90) * sign; // We have to combine the components so that the Y component is the same because its already normalized // But we have to normalize the x, z components based on the Y component return Vector3(x / (1 - y), y, z / (1 - y)); }
In other words you're seeking a vector from hitPosition towards the projection of goalPoint along the Y axis. You don't need trigonometry for this. A vector (X,Y,Z) is perpendicular to the normal of the plane if it satisfies: X*normalVector.X + Y*normalVector.Y + Z*normalVector.Z == 0 (See dot product.) That vector points towards the projection of goalPoint along Y axis if X = deltaX Z = deltaZ Substituting and solving for Y: Y = -(deltaX*normalVector.X + deltaZ*normalVector.Z)/normalVector.Y You can normalize the result at the end if needed. Putting it all together: Vector3 DetermineVector(Vector3 normalVector, Vector3 hitPosition, Vector3 goalPoint) { float deltaX = goalPoint.X - hitPosition.X; // TO - FROM float deltaY = goalPoint.Y - hitPosition.Y; // TO - FROM float deltaZ = goalPoint.Z - hitPosition.Z; // TO - FROM float X = deltaX; float Y = -(deltaX*normalVector.X + deltaZ*normalVector.Z)/normalVector.Y; float Z = deltaZ; // optionally normalize: float length = sqrt(X*X + Y*Y + Z*Z); X /= length, Y /= length, Z /= length; return Vector3(X, Y, Z); }
74,104,611
74,104,634
I don't know why my c++ arrays are not working
The errors I received are these: error: 'NoOfHours' was not declared. Its the same with taxrate, salary, tax, and netpay. The output I'm looking for is a table using the gathered data from the user: | Name | Position | No. Of Hours | Salary |Tax|netpay| | -------- | -------------- |----------------|------------|---|-| | Mary | Laborer | 8 |500|25|475 | john | Laborer | 8 |500|25|475 Something like the table above. #include <iostream> #include <iomanip> using namespace std; int main() { int Laborer = 500; int Foreman = 750; int Manager = 1500; int RatePerDay [3]; int n; cout << "Enter No. of Employees: "; cin >>n; cout << endl; string Name [n]; string Position [n]; for ( int i=0; i<n; i++){ float NoOfHours [i]; float TaxRate [i]; float Salary [i]; float Tax [i]; float NetPay [i]; float TotalSalary[i]; float TotalTax[i]; float TotalNetPay[i]; cout << "Enter Name: "; cin >> Name[i]; cout << "Enter the position: "; cin >> Position[i]; cout << "Enter No. of Hours Worked: "; cin >> NoOfHours[i]; cout << endl; if (Position[i]=="Laborer") {RatePerDay[i] = Laborer; TaxRate[i] = 0.05;} else if (Position[i]=="Foreman") {RatePerDay[i] = Foreman; TaxRate[i] = 0.08;} else (Position[i]=="Manager"); {RatePerDay[i] = Manager; TaxRate[i] = 0.10;} Salary[i] = NoOfHours[i] * RatePerDay[i] / 8; Tax[i] = Salary[i] * TaxRate[i]; NetPay[i] = Salary[i] - Tax[i]; TotalSalary[i] = TotalSalary[i] + Salary[i]; TotalTax[i] = TotalTax[i] + Tax[i]; TotalNetPay[i] = TotalNetPay[i] + NetPay[i]; } cout <<setw(1) <<right<< "Name of Employee" <<setw(15) <<right<< "Position" <<setw(15) <<right<< "No of Hours" <<setw(15) <<right<< "RatePerDay" <<setw(15) <<right<< "Salary" <<setw(15) <<right<< "TaxRate" <<setw(15) <<right<< "Tax" <<setw(15) <<right<< "NetPay"<<endl; cout << "============================================================================================================================"<<endl; // I received the errors here. for ( int i=0; i<n; i++){ cout << setw(23) <<setfill(' ')<<left<< Name[i] << setw(17) <<setfill(' ')<<left<< Position[i] << setw(14) <<setfill(' ')<<left<< NoOfHours[i] << setw(17) <<setfill(' ')<<left<< RatePerDay[i] << setw(14) <<setfill(' ')<<left<< Salary[i] << setw(18) <<setfill(' ')<<left<< TaxRate[i] << setw(12) <<setfill(' ')<<left<< Tax[i] << setw(15) <<setfill(' ')<<left<< NetPay[i]<<endl; } return 0; }
Most of your arrays are declared inside of the 1st loop, so they are out of scope when the 2nd loop tries to access them. Fix your code's indentation, then the problem will be easier to see. You need to move the affected arrays outside of the 1st loop, at the same level as the RatePerDay, Name, and Position arrays 1. 1: BTW, variable-length arrays are not standard C++. Use std::vector instead when you need an array whose sizes is not known until runtime.
74,105,193
74,105,236
What is the difference between "int x" and "(int)x"?
I wanted to know the difference in C++ of the following examples. Why example two is not applicable? First example: void ReceiveServerConnect(BYTE* ReceiveBuffer) { LPPRECEIVE_SERVER_ADDRESS Data = (LPPRECEIVE_SERVER_ADDRESS) ReceiveBuffer; } Second example: void ReceiveServerConnect(BYTE* ReceiveBuffer) { LPPRECEIVE_SERVER_ADDRESS Data = LPPRECEIVE_SERVER_ADDRESS ReceiveBuffer; }
Your first example, with the parentheses, is doing a cast from one type to another. It's an old-style C cast which is a very blunt instrument. For C++ you should prefer one of the new styles: LPPRECEIVE_SERVER_ADDRESS Data = static_cast<LPPRECEIVE_SERVER_ADDRESS>(ReceiveBuffer); The second example is simply bad syntax and should be rejected by the compiler with an error. Without the parentheses it looks like you're trying to declare a variable in the middle of an expression. That's just the syntax that C++ has adopted, best to just accept it and not try to make much sense of it.
74,105,699
74,106,122
Getting top layer of 3d noise
I've generated a cubic world using FastNoiseLite but I don't know how to differentiate top level blocks as grass and bottom one's dirt when using 3d noise. TArray<float> CalculateNoise(const FVector& ChunkPosition) { Densities.Reset(); // ChunkSize is 32 for (int z = 0; z < ChunkSize; z++) { for (int y = 0; y < ChunkSize; y++) { for (int x = 0; x < ChunkSize; x++) { const float Noise = GetNoise(FVector(ChunkPosition.X + x, ChunkPosition.Y + y, ChunkPosition.Z + z)); Densities.Add(Noise - ChunkPosition.Z); } } } return Densities; } void AddCubeMaterial(const FVector& ChunkPosition) { const int32 DensityIndex = GetIndex(ChunkPosition); const float Density = Densities[DensityIndex]; if (Density < 1) { // Add Grass block } // Add dirt block } void GetNoise(const FVector& Position) const { const float Height = 280.f; if (bIs3dNoise) { FastNoiseLiteObj->GetNoise(Position.X, Position.Y, Position.Z) * Height; } FastNoiseLiteObj->GetNoise(Position.X, Position.Y) * Height; } This is the result when using 3D noise. 3D Noise result But if I switch to 2D noise it works perfectly fine. 2D Noise result
This answer applies to Perlin like noise. Your integer chunk size is dis-contiguous in noise space. 'Position' needs to be scaled by 1/Height. To scale the noise as a contiguous block. Then scale by Height. If you were happy with the XY axes(2D), you could limit the scaling to the Z axis: FastNoiseLiteObj->GetNoise(Position.X, Position.Y, Position.Z / Height) * Height; This adjustment provides a noise continuous Z block location with respect to Position(X,Y). Edit in response to comments Contiguous: The noise algorithm guarantees continuous output in all dimensions. By sampling every 32 pixels (dis-contiguous sampling), The continuity is broken, on purpose(?) and augmented by the Density. To guarantee a top level grass layer: Densities.Add(Noise + (ChunkPosition.Z > Threshold) ? 1: 0); Your code- ChunkPosition.Z made grass thicker as it went down. Add it back if you wish. To add random overhangs/underhangs reduce the Density threshold randomly: if (Density < (rnd() < 0.125)? 0.5 : 1) I leave the definition of rnd() to your preferred random distribution. To almost always have overhangs, requires forward lookup of the next and previous blocks' Z in noise. Precalculate the noise values for the next line into alternating arrays 2 wider than the width to support the edges set at 0. The algorithm is: // declare arrays: currentnoise[ChunkSize + 2] and nextnoise[ChunkSize +2] and alpha=.2; //see text for (int y = 0; y < ChunkSize; y++) // note the reorder y-z-x { // pre load currentnoise for z=0 currentnoise[0] = 0; currentnoise[ChunkSize+1] = 0; for (int x = 0; x < ChunkSize; x++) { currentnoise[x + 1] = GetNoise(FVector(ChunkPosition.X + x, ChunkPosition.Y + y, ChunkPosition.Z)); } for (int z = 1; z < ChunkSize -2; z++) { nextnoise[0] = 0; nextnoise[ChunkSize+1] = 0; // load next for (int x = 0; x < ChunkSize; x++) { nextnoise[x + 1] = GetNoise(FVector(ChunkPosition.X + x, ChunkPosition.Y + y, ChunkPosition.Z + z+1)); } // apply current with next for (int x = 0; x < ChunkSize; x++) { Densities.Add(currentnoise[x + 1] * .75 + nextnoise[x+2] * alpha + nextnoise[x] * alpha); } // move next to current in a memory safe manor: // it is faster to swap pointers, but this is much safer for portability for (int i = 1; i < ChunkSize + 1; i++) currentnoise[i]=nextnoise[i]; } // apply last z(no next) for (int x = 0; x < ChunkSize; x++) { Densities.Add(currentnoise[X + 1]); } } Where alpha is approximately between .025 and .25 depending on preferred fill amounts. The 2 inner most x for loops could be streamlined into 1 loop, but left separate for readability.(it requires 2 preloads)
74,105,980
74,106,066
The erase function of strings in c++
well I was doing this problem from leetcode " https://leetcode.com/problems/valid-palindrome/ " and to remove the punctuations I used this for (auto i:s) { if (ispunct(i)) { s.erase(remove(s.begin(), s.end(), i), s.end()); continue; } } but when it runs it leaves some punctuation characters in the string like this: ip-> "Marge, let's "[went]." I await {news} telegram." op-> "margelets[wentiawaitnewstelegram"
Modifying a string (or any other collection) while looping over it is a poor idea. Your iterator into the string is based on the state of the string at the beginning of your loop. Changing the state of the string inside the loop may lead to unexpected behavior of your iterator. Rather you may want to create a new string without the offending characters. #include <iostream> #include <string> #include <algorithm> #include <cctype> int main() { std::string s1 = "Hello world!"; std::string s2; std::copy_if(s1.begin(), s1.end(), std::back_inserter(s2), [](auto ch) { return !std::ispunct(ch); }); std::cout << s2 << std::endl; return 0; }
74,105,996
74,122,916
Is it possible to use the COM DLL without register in Registry using RegAsm.exe?
I need to use the C# dll from C++ code. Is there any way to use the dll without register it into registry. Because register in registry needs administrative privilege. If any suggestion please let me know
I solved this Problem by Register the COM dll in HKEY_CURRENT_USERS hive by this code https://stackoverflow.com/a/35789844/19616470
74,106,392
74,106,439
const function modifying data in Doubly Linked List
I have created a doubly linked list. in the list, there is a function that is const, and is not supposed to modify the object. but it is modifyind I dont know why. #include<iostream> using namespace std; class Node { public: int data; Node* prev; Node* next; Node(int val) :data(val), next(NULL), prev(NULL) {} }; class List { Node* head; Node* tail; public: List() :head(NULL), tail(NULL) {} void addToTail(int val) { Node* temp = new Node(val); if (head == NULL) { head = temp; tail = temp; } else { tail = head; while (tail->next != NULL) { tail = tail->next; } tail->next = temp; temp->prev = tail; tail = temp; } } int search(int val) const { if (head->data == val) head->data = 12; return head->data; } }; int main() { List l; l.addToTail(1); l.addToTail(2); l.addToTail(3); l.addToTail(4); l.addToTail(5); int c = l.search(1); //c = 102; cout << c; } Now I have tried to use const before the return type, but obviously it doesnt matter. it does not affect the result; in the search(int val) function, I am sending a value to check if 'head->data' is equal to the 'val', it should not modify the 'head->data = 12' because the function is const. but it is doing this.
The const qualifier for the member function only tells the compiler that you won't modify this object. And you don't do that: You modify head->data which is another object. It would be a different issue if you tried to reassign the variables head or tail.
74,106,522
74,106,574
What differs between parentheses and curly in std::tuple?
Well today I met a werid behavior when using std::tuple() and std::tuple{}. Here is an easy demo: #include <iostream> #include <tuple> #define rd ({ int x = (std::cin >> x, x); x; }) template <typename... Args> void log(const Args &...args) { ((::std::cout << args << ", "), ...); } auto main() -> int { auto [a, b] = std::tuple(rd, rd); auto [c, d] = std::tuple{rd, rd}; log(a, b, c, d); return {}; } Run: echo '1 2 3 4' > input clang++ -std=c++17 demon.cpp ./a.out < input g++ -std=c++17 demon.cpp ./a.out < input cat demon.cpp And I got 2 different results: 1, 2, 3, 4 and 2, 1, 3, 4. That's out of my expectation. I turned to my friends and got the reply of "The macro rd is a unspecific behaivor". However, I am still confused with this answer after learning something about unspecific behaivor.
Your friends are correct. The unspecified behaviour occurs because the evaluation order of function arguments is not specified, it can happen in any order and can change between calls. Meaning the order of std::cin is not guaranteed. The compiler is free to reorder them as it sees fit. This applies to std::tuple(), hence the incorrect output. On the other hand for braced-init-list, the order is fixed left-to-right, therefore std::tuple{} is safe and the output is guaranteed. Furthermore, in rd, having braced-statements in expressions is not standard C++ so you are at the mercy of your compiler. I would seriously recommend macro-less refactoring, hiding std::cin in an expression seems like asking for trouble. Why not simple read_int() function or generic read_T? Then you can generalize to read_Ts<T1,T2,T3...> with explicit sequencing. For example: template<typename T> T read_T(){ T x; std::cin>> x; return x; } template<typename...T> auto read_Ts(){ return std::tuple{read_T<T>()...}; }