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,331,990
74,332,143
check and protect a thread in c++
Currently, I created a simple thread to clear memory: BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: CreateThread(0, 0, test, 0, 0, 0); break; case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: case DLL_PROCESS_DETACH: break; } return TRUE; } Code: DWORD WINAPI test(LPVOID lpvParam) { memo: Sleep(10000); SetProcessWorkingSetSize(GetCurrentProcess(), 102400, 614400); goto memo; } Is there any way to protect this thread? And prevent it from being paused with some external program (such as Process Hacker 2)? Example: if the thread is running, returns true, if it is externally paused or interrupted, returns false and closes the program with ExitProcess()? I tried different methods like std::thread thread.join(). thread.joinable() None of them worked.
prevent thread from being paused with some external program (such as Process Hacker 2)? Instead of creating a new thread to run your code periodically, create a waitable timer with CreateWaitableTimer and schedule it with SetWaitableTimer. The timer runs the callback in the thread that called SetWaitableTimer, so that there is no other thread to pause. That also solves the problem that threads must not be created in DllMain.
74,332,135
74,332,239
How to read a file in Python written out by C++
I have one program written in C++ that outputs the data from several different types of arrays. For simplicity, I'm using ints and just writing them out one at a time to figure this out. I need to be able to read the file in on Python, but clearly am missing something. I'm having trouble translating the concepts from C++ over to Python. This is the C++ I have that's working - it writes out two numbers to a file and then reads that file back in (yes, I have to use the ostream.write() and istream.read() functions - that's how at the base level the library I'm using does it and I can't change it). int main(int argc, char **argv) { std::ofstream fout; std::ifstream fin; int outval1 = 1234; int outval2 = 5678; fout.open("out.txt"); fout.write(reinterpret_cast<const char*>(&outval1), sizeof(int)); fout.write(reinterpret_cast<const char*>(&outval2), sizeof(int)); fout.close(); int inval; fin.open("out.txt"); while (fin.read(reinterpret_cast<char*>(&inval), sizeof(int))) { std::cout << inval << std::endl; } fin.close(); return 0; } This is what I have on the Python side, but I know it's not correct. I don't think I should need to read in as binary but that's the only way it's working so far with open("out.txt", "rb") as f: while (byte := f.read(1)): print(byte)
In the simple case you have provided, it is easy to write the Python code to read out 1234 and 5678 (assuming sizeof(int) is 4 bytes) by using int.from_bytes. And you should open the file in binary mode. import sys with open("out.txt", "rb") as f: while (byte := f.read(4)): print(int.from_bytes(byte, sys.byteorder)) To deal with floats, you may want to try struct.unpack: import struct byte = f.read(4) print(struct.unpack("f", byte)[0])
74,332,440
74,332,699
How to use "type ... pack-name" parameter pack in C++?
The cppreference page on parameter pack states there is a parameter pack like this: type ... pack-name(optional) (1) But how do you use it? This doesn't work and the error is syntactical: template<int... Ints> int sum_2_int(Ints... args) { return (int)(args + ...); } I can't figure out how to use this thing from the description and I don't see an example of the usage anywhere on that page. I may have just skipped it because I am very inexperienced in this part of c++. EDIT1: I am not trying to sum an arbitrary amount of integers or whatever types. I've written this function because of my complete lack of understanding of how and where to use this type of parameter pack since I assumed it will be similar to the type (2) typename|class ... pack-name(optional). EDIT2: Now I know that trying to use Ints... args as a parameter in function definition is futile. I made a new snippet, that works now here. If you know more examples of the usage of this type of parameter pack, please share.
So, what I've learned about type (1) parameter pack: It is INCORRECT to use as a parameter in the function definition, since template<int... Ints> int foo(...) {...} just means that you should later use your function as int i = foo<1,2,3,4,...>(...); It can be used as an argument to some function after the expansion happens: // parameter pack type [2] typename|class ... pack-name(optional) template <typename... Types> int sum_to_int(Types... args) { return (int)(args + ...); // fold expression used here } // parameter pack [1] type ... pack-name(optional) template <int... Ints> int sum_ints_statically() { return sum_to_int(Ints...); } int main() { return sum_ints_statically<1,2,3,4,5>(); // will return 15! } Thanks Evg and user17732522 for helping me to find the answer. Please add more usage examples if you know more!
74,332,629
74,332,715
Realloc throws stack overflow sporadically in program that calculates large integers
void inf_int::Sub(const char num, const unsigned int index) { if (this->length < index) { char* tmp = (char*)realloc(this->digits, index + 1); if (tmp == NULL) { cout << "Memory reallocation failed, the program will terminate." << endl; free(this->digits);// provided that the destructor does not call free itself exit(0); } this->digits = tmp; this->length = index; this->digits[this->length] = '\0'; } if (this->digits[index - 1] < '0') { this->digits[index - 1] = '0'; } this->digits[index - 1] -= num + '0'; if (this->digits[index - 1] < '0') { this->digits[index - 1] += 10; Sub('1', index + 1); } } I am trying to make a program that calculates really large integers, using character arrays to store each digit. The compiler keeps throwing overflow error in char* tmp = (char*)realloc(this->digits, index + 1); after 2 or so debugs, then after throwing errors for a few times, works again for another two tries, then repeats. Can anybody point out where I am doing wrong? Thank you. digits is char* digits; inf_int::inf_int() { this->digits = new char[2]; this->digits[0] = '0'; this->digits[1] = '\0'; this->length = 1; this->thesign = true; } inf_int::inf_int(int n) { char buf[100]; if (n < 0) { this->thesign = false; n = -n; } else { this->thesign = true; } int i = 0; while (n > 0) { buf[i] = n % 10 + '0'; n /= 10; i++; } if (i == 0) { new (this) inf_int(); } else { buf[i] = '\0'; this->digits = new char[i + 1]; this->length = i; strcpy(this->digits, buf); } } inf_int::inf_int(const char* str) { char* answer = new char[strlen(str)]; if (str == NULL) { new (this) inf_int(); } else { strcpy(answer, str); if (answer[0] == '-') { char* solution = new char[strlen(str)]; this->thesign = false; for (unsigned int i = 1; i < strlen(str); i++) { solution[strlen(str) -1-i] = answer[i]; } solution[strlen(str)] = '\0'; this->digits = new char[strlen(str)+1 ]; this->length = strlen(str); strcpy(this->digits, solution); } else { char* solution = new char[strlen(str)+1];; this->thesign = true;//123 3 for (unsigned int i = 0; i < strlen(str); i++) { solution[strlen(str) - i-1] = answer[i]; } solution[strlen(str)] = '\0'; this->digits = new char[strlen(str)+1 ]; this->length = strlen(str); strcpy(this->digits, solution); } } }
this->digits = new char[2]; This class member is initially allocated using new. char* tmp = (char*)realloc(this->digits, index + 1); This is undefined behavior. realloc is for C code that used malloc to allocate memory. A realloc of something that was originally newed always ends in tears. Everything that follows from this point on is undefined behavior. new (this) inf_int(); including this, which does not accomplish anything useful, except more undefined behavior (for completely different reasons). It seems that, based on the entirety of the shown code, it was likely stitched together from the results of multiple keyword searches, from some search engine, instead of applying knowledge that was acquired from studying with a C++ textbook. This approach to writing C++ code rarely produces working results; additionally modern C++ rarely needs to use new for basic logic of the kind shown here, instead C++'s containers handle all the memory allocation for you, and correctly. For example, std::vector does pretty much what a good portion of this code is trying to accomplish -- allocating an initial buffer and resizing it, when needed. This is exactly what std::vector is for, and more information on how to use it will be found in your favorite C++ textbook.
74,332,725
74,333,952
How to summing element in array using taskloop on OMP
I was trying to using taskloop to finding sum of element in array. #include <iostream> #include <omp.h> using namespace std; #define NUMTHREAD 6 #define SIZE 100 int main() { int* n = new int [SIZE]; for (int i = 0; i < SIZE; ++i) { n[i] = 1; } long sum =0; #pragma omp parallel num_threads(NUMTHREAD) { #pragma omp taskloop for (int i = 0; i < SIZE; i++) { sum += n[i]; } } cout << sum<< "\n"; return 0; } but output is 600 It's should be 100 I don't know why sum is shared. I was trying to made sum not shared and for each thread. #pragma omp parallel num_threads(NUMTHREAD) { #pragma omp taskloop private(sum) for (int i = 0; i < SIZE; i++) { sum += n[i]; } } but Output is 0 IDK why?
The taskloop construct is a task-generating construct, not a worksharing-loop construct. You can read the following in OpenMP specification: The taskloop construct is a task generating construct. When a thread encounters a taskloop construct, the construct partitions the iterations of the associated loops into explicit tasks for parallel execution. In your case 6 threads encounter the taskloop construct, therefore the loop is executed 6 times, and you got a bigger result than expected. To correct it you have to i) make sure that only a single thread executes the tasks generating construct, or ii) use a worksharing-loop construct. There is a race condition at line sum += n[i];, as different threads update sum simultaneously. To correct it the best option is to use reduction (reduction(+:sum)) In the second case the sharing attribute of sum is private, so the variable sum will be privatized. It means that a local variable is created, and only the value of the local variable is changed. It does not change the value of sum in the enclosing context, therefore you got 0. To sum up, here are the 2 alternatives mentioned above to correct your code: i) using single construct and taskloop: #pragma omp parallel num_threads(NUMTHREAD) #pragma omp single nowait { #pragma omp taskloop reduction(+:sum) for (int i = 0; i < SIZE; i++) { sum += n[i]; } } ii) using a worksharing-loop construct: #pragma omp parallel num_threads(NUMTHREAD) { #pragma omp for reduction(+:sum) for (int i = 0; i < SIZE; i++) { sum += n[i]; } } Some minor, off-topic comments: The array (allocated by new operator) is never freed, you should use delete to deallocate it. As pointed out by @VictorEijkhout it is even better if you do not use new at all. Use vector or array from the std library. You should prefer const/constexpr int SIZE=100; over #define SIZE 100. More details can be found e.g. here. You should consider reading Why is "using namespace std;" considered bad practice?
74,332,999
74,333,188
Why does this freestanding program segfault?
I've found an interesting behavior that I cannot explain. I wrote this very simple program that segfaults without apparent reason. Please, can someone explain what is happening here? The program is run in Ubuntu (I don't know if that matters). No includes, no libraries, no link to stdlib. No dependencies whatsoever. I've tested that the segfault goes away when any of the following happens: stdlib is linked (and renamed _start to main, removed extern "C", etc.) GCC is used Optimizations are enabled The following is the one and only code file for the program, lets call it main.cpp. Build it with: clang main.cpp -nostdlib. struct A { A () = default; A (const A &) = default; // A (A &) = default; char * a = nullptr; unsigned long long b; }; struct ConvertibleToA { ConvertibleToA() = default; // default constructor operator A() { return m_a; } // conversion to type A A m_a; }; extern "C" void _start() { ConvertibleToA my_convertible{}; A my_a = my_convertible; }
Check your stack alignment. For the SysV ABI, rsp is guaranteed to be 16-bytes aligned at program entry. However, a normal function expect rsp to be 16-bytes+8 aligned, because of the address pushed by call. Clang uses SSE aligned instructions which will crash, GCC doesn't.
74,333,029
74,333,106
How to make increment/decrement static variable for an API?
#include <iostream> class Test { public: static int numelem; Test() {} ~Test() {} int increment(); }; int Test::numelem = 0; int Test::increment() { return ++Test::numelem; } So I want to make a counter for my Stacks data structure. Whenever I push, it increments and when popped it decrements. My code works, but int Test::numelem = 0; is a global variable. I tried using inline but unfortunately I have C++14. I only put the static int numelem instead of the whole Stack class to focus on one feature. Is there an alternative way I can put int Test::numelem = 0; inside the class without getting any error?
but int Test::numelem = 0; is a global variable. Technically, it is not a global variable but a class static member. Functionally they behave very similarly. Is there an alternative way I can put int Test::numelem = 0; inside the class without getting any error? unfortunately I have C++14. With C++14 the out-of-class definition for a nonconst static data member should be in the same namespace scope where the class was defined(global namespace in your example). So there is no way of defining a nonconst static data member inside the class in c++14 as we can't use inline in c++14 and the only way of defining a nonconst static data member is to put a definition at namespace scope. This can be seen from class.static.data: The declaration of a static data member in its class definition is not a definition and may be of an incomplete type other than cv-qualified void. The definition for a static data member shall appear in a namespace scope enclosing the member's class definition. But with C++17 we can use inline to define a non-const static data member inside the class.
74,333,276
74,333,326
Get vertex buffer bound to vertex array
I'm writing an OpenGL application, and the problem I'm facing now is as follows: Let us say I have a Vertex Array, with its ID. However, I do not have its bound vertex buffer ID at hand. I am in need of the Buffer ID for an operation. SO, is it possible to retrieve current buffer binding from vertex array? Note that I have come across glGetIntegerv, however I think it only retrieves current buffer binding, NOT vertex array binding
Let us say I have a Vertex Array, with its ID. However, I do not have its bound vertex buffer ID at hand. In a well-behaved application, that should not be possible. It was your application that put that buffer into that VAO. Therefore, you should already know what buffer is attached to it. It's a question you don't need to ask. However, if you have no other choice but to ask OpenGL a question that you ought to know the answer to, you must first bind the VAO to the context. If you're not using the separate attribute format API, then you can use glGetVertexAttribiv with GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING, specifying the attribute index you're interested in querying. If you want to use the separate attribute format API, you need to use glGetIntegeri_v with GL_VERTEX_BINDING_BUFFER, specifying the binding index to query. If you're using DSA (which requires using the separate attribute format), then you can use glGetVertexArrayIndexediv, with GL_VERTEX_BINDING_BUFFER and the appropriate binding index.
74,333,483
74,333,778
How to Read in a String With Spaces into a Linked List?
So essentially I am reading data into this linked list, then after each node is inserted (front or back) I display the nodes. When I do this, everything works fine with names without spaces, but if I use first and last with a space it does not function properly and will separate the string(s) with spaces into 2 different nodes, usually opposite of each other. Here is my code to read the data that is entered: struct node *new_node() { struct node *new1=(struct node *)malloc(sizeof(struct node)); cin >> new1 -> string_val; new1 -> next=NULL; return new1; } The constructor for the struct 'node' is as follows: struct node { char string_val[20]; struct node *next; };
Assuming the node definition needs to be the same and input is through stdin and all one one line for the following answer. Due to use of char [20] input from stdin is truncated to prevent overflow or segfault. Given the following node (preserving OP's node definition): struct node { char string_val[20]; struct node *next; }; Node can be constructed with following: struct node *new_node() { // Create new node node * newNode = new node; // Get line std::cin.getline(newNode->string_val, 20); // Set next node to nullptr newNode->next = nullptr; return newNode; } If node definition can be changed and std::string can be used then this changes to the following: #include <string> struct node { std::string string_val; struct node *next; }; struct node *new_node() { // Create new node struct node * newNode = new node; // Get line std::getline(std::cin, newNode->string_val); newNode->next = nullptr; return newNode; }
74,333,889
74,333,943
An alias for a function pointer declared by "using"
I have declared an alias for a function pointer with "using" keyword, but I don't know how to use the alias. In UpdateState function of Person class, I want to substitude m_state for the return value of the function corresponding to the current state and the one you want to transition to next. However, the error below occurs on the line 38 in Person.cpp and I don't know how to correct the line. I think I am using the alias array wrong. error C2064: term does not evaluate to a function taking 1 arguments Person.h #pragma once enum STATE { A, B, C, D, E, STATE_NUM, }; class Person { public: Person(); ~Person(); void UpdateState(); STATE IsInStateA(char nextState); STATE IsInStateB(char nextState); STATE IsInStateC(char nextState); STATE IsInStateD(char nextState); STATE IsInStateE(char nextState); private: STATE m_state; }; Person.cpp #include <iostream> #include "Person.h" Person::Person() :m_state(A) { } Person::~Person() { } void Person::UpdateState() { char inputArray[] = { 'a','b','c','d','e' }; char nextStateInput; while (1) { std::cout << "Please input the state you want to transition to next: "; std::cin >> nextStateInput; for (int i = 0; i < sizeof inputArray / sizeof inputArray[0]; ++i) { if (nextStateInput == inputArray[i]) { break; } } std::cout << "Please enter one of the letters a-e." << std::endl; } using StateFunc = STATE(Person::*)(char); StateFunc stateFuncTable[STATE_NUM] = { IsInStateA, IsInStateB, IsInStateC, IsInStateD, IsInStateE }; for (int i = 0; i < STATE_NUM; ++i) { if (nextStateInput == inputArray[i]) { m_state = stateFuncTable[m_state](nextStateInput); //The error occurs on this line. } } } STATE Person::IsInStateA(char nextState) { switch (nextState) { case 'b': return B; case 'd': return D; default: return A; } } STATE Person::IsInStateB(char nextState) { switch (nextState) { case 'c': return C; case 'd': return D; case 'e': return E; default: return B; } } STATE Person::IsInStateC(char nextState) { switch (nextState) { case 'b': return B; default: return C; } } STATE Person::IsInStateD(char nextState) { switch (nextState) { case 'a': return A; case 'e': return E; default: return D; } } STATE Person::IsInStateE(char nextState) { switch (nextState) { case 'a': return A; case 'b': return B; default: return E; } }
To get a pointer to a non-static member the syntax is &ClassName::membername. Additionally, a call using the pointer to member function is made using either .* or ->*. Below is the modified working example where I've added comments to show the changes i've made: void Person::UpdateState() { char inputArray[] = { 'a','b','c','d','e' }; char nextStateInput; while (1) { std::cout << "Please input the state you want to transition to next: "; std::cin >> nextStateInput; for (int i = 0; i < sizeof inputArray / sizeof inputArray[0]; ++i) { if (nextStateInput == inputArray[i]) { break; } } std::cout << "Please enter one of the letters a-e." << std::endl; } using StateFunc = STATE(Person::*)(char); StateFunc stateFuncTable[STATE_NUM] = { &Person::IsInStateA, //added &Person:: here &Person::IsInStateB, //added &Person:: here &Person::IsInStateC, //added &Person:: here &Person::IsInStateD, //added &Person:: here &Person::IsInStateE //added &Person:: here };; for (int i = 0; i < STATE_NUM; ++i) { if (nextStateInput == inputArray[i]) { //---------------------vvvvvvv---------------------->correct syntax using ->* m_state = (this->*stateFuncTable[m_state])(nextStateInput); } } } Working demo With C++17 you can use std::invoke instead of ->* as shown below: m_state = std::invoke(stateFuncTable[m_state], this, nextStateInput); Demo C++17
74,334,362
74,334,405
What's the difference b/w map[key] vs map.count(key) ? (particularly in this code)
So I was Solving a leetcode Problem and one dumb mistake made in debugg for more than an hour. Leetcode Question Answers(both working and not working) Working code: ` class Solution { public: int longestPalindrome(vector<string>& words) { unordered_map<string,int> map; for(string s:words){ map[s]++; } bool isOdd = false; int ans = 0; for(auto i:map){ string rv = i.first; reverse(rv.begin(),rv.end()); if(i.first[0]==i.first[1]){ if(i.second%2==0) ans+=i.second; else{ ans+= i.second-1; isOdd = true; } } else if(i.first[0]<i.first[1] && map.count(rv)){ ans += 2*min(i.second,map[rv]); } } if(isOdd){ ans++; } return 2*ans; } }; Not working code: ` class Solution { public: int longestPalindrome(vector<string>& words) { unordered_map<string,int> map; for(string s:words){ map[s]++; } bool isOdd = false; int ans = 0; for(auto i:map){ string rv = i.first; reverse(rv.begin(),rv.end()); if(i.first[0]==i.first[1]){ if(i.second%2==0) ans+=i.second; else{ ans+= i.second-1; isOdd = true; } } else if(i.first[0]<i.first[1] && map[rv]){ ans += 2*min(i.second,map[rv]); } } if(isOdd){ ans++; } return 2*ans; } }; The only difference between both code is map[rv] ==> map.count(rv) test case which is giving error: ["oo","vv","uu","gg","pp","ff","ss","yy","vv","cc","rr","ig","jj","uu","ig","gb","zz","xx","ff","bb","ii","dd","ii", "ee","mm","qq","ig","ww","ss","tt","vv","oo","ww","ss","bi","ff","gg","bi","jj","ee","gb", "qq","bg","nn","vv","oo","bb","pp","ww","qq","mm","ee","tt","hh","ss","tt","ee","gi","ig","uu","ff","zz", "ii","ff","ss","gi","yy","gb","mm","pp","uu","kk","jj","ee"] Can anyone please help me? I've tried googling this stuff but couldn't find it. then i've tried asking few people on discord. but no progress. I just wanna know why above(not working part) code in not working. What is the deal with map[key] and map.count(key)? When should i use which one?
std::map.count() will check, if an element with a given key exists. It will not modify the container. Please see here. It is even defined as constto indicate that fact. The std::maps index operator is different. It returns a reference to the value that is mapped to a key equivalent to key, performing an insertion if such key does not already exist. So, if the key does not exist, it will add an entry to the map, with this new key. Therefore your second code cannot work.
74,335,759
74,335,815
How do I use member functions to a standard library ranges operation
I need to find all regular files in a directory, and would like to use the C++20 ranges (not Eric Niebler's range-v3) library. I came up with the following code: namespace fs = std::filesystem; std::vector<fs::directory_entry> entries{ fs::directory_iterator("D:\\Path"), fs::directory_iterator() }; std::vector<fs::path> paths; std::ranges::copy(entries | std::views::filter([](const fs::directory_entry& entry) { return entry.is_regular_file(); }) | std::views::transform([](const fs::directory_entry& entry) { return entry.path(); }), std::back_inserter(paths)); This works, but I'm uncomfortable with the additional boilerplate of using lambdas; I'm used to the Java 8 streams library, and I don't see why I can't just use member functions directly. This was my first attempt at refactoring: std::ranges::copy(entries | std::views::filter(fs::directory_entry::is_regular_file) | std::views::transform(fs::directory_entry::path), std::back_inserter(paths)); This resulted in compiler errors: error C3867: 'std::filesystem::directory_entry::is_regular_file': non-standard syntax; use '&' to create a pointer to member error C3889: call to object of class type 'std::ranges::views::_Filter_fn': no matching call operator found ... So I tried this: std::ranges::copy(entries | std::views::filter(&fs::directory_entry::is_regular_file) | std::views::transform(&fs::directory_entry::path), std::back_inserter(paths)); This fixed the first error, but not the second: error C3889: call to object of class type 'std::ranges::views::_Filter_fn': no matching call operator found ... So I found Using member variable as predicate, which looked promising, so I tried: std::ranges::copy(entries | std::views::filter(std::mem_fn(&fs::directory_entry::is_regular_file)) | std::views::transform(std::mem_fn(&fs::directory_entry::path)), std::back_inserter(paths)); This resulted in new compiler errors: error C2672: 'std::mem_fn': no matching overloaded function found ... Note, std::bind doesn't appear to work either. Any help would be appreciated, thanks!
Just &fs::directory_entry::is_regular_file as argument is in principle correct, assuming that there is only one non-template overload for the function. Pointers can only point to one function (or function template specialization), not to an overload set. However per standard there are two overloads for directory_entry::is_regular_file. To select one of them for the pointer you would need to add an explicit cast directly around the pointer with the target pointer type matching the overload's type you want to select. In this special case the & operator will then select the function matching the target type from the overload set. But even then, the standard says that behavior is unspecified if you try to take any reference or pointer to a non-static member of a standard library class. This basically allows the standard library implementer to change the overload set as long as direct calls to the functions behave as if there were exactly the overloads specified in the standard. Using lambdas as in your first example is the intended use and the only one that is guaranteed to work. You can reduce the boiler-plate a bit though. You don't need to repeat the argument type. [](auto& entry) { return entry.is_regular_file(); } will work as well. If you need this often and you are annoyed by typing out the lambdas, you can also write yourself a macro for it. Something like #define LIFT_MEMBER_FUNC(func) \ ([](auto&& obj, auto&&... args) \ noexcept(noexcept((decltype(obj)(obj)).func(decltype(args)(args)...))) \ -> decltype(auto) \ requires requires { (decltype(obj)(obj)).func(decltype(args)(args)...); } \ { return (decltype(obj)(obj)).func(decltype(args)(args)...); }) and then std::views::filter(LIFT_MEMBER_FUNC(is_regular_file)) Note that I have not tested the macro and that there may be edge cases I haven't considered. Take it as a guideline to how such a macro may look. Simplified versions that drop the requires clause (making it non-SFINAE-friendly) or that drop the noexcept line (making it not forward noexcept) or replacing decltype(X)(X) with just X (making it not perfectly-forwarding) would also work in most typical situations. The noexcept forwarding expects that there won't be any copy/move constructor call for the lambda return value, so it is correct only for C++17 or later and the requires clause would need to be replaced with SFINAE or dropped before C++20.
74,336,301
74,336,780
Efficient way to generate random numbers with weights
I need to frequently generate a large number of random numbers in my project, so I am seeking an efficient way to do this. I have tried two ways: (i) using random() and srand(); (ii) using C++ random library. I tried on the following example: I need to generate 100000000 numbers, from {0, 1, 2, 3}, with weights {0.1, 0.2, 0.3, 0.4}. And from the example, I found that (i) is faster than (ii). (i) requires ~1.3s while (ii) requires ~4s, both using release builds. Is there any other more efficient way to generate random numbers with weights? This is exactly the bottleneck of my program. Note that, this is just an example. The codes inside the loop in the example are just part of the codes inside the loop in my program. For example, each time generating random numbers has different weights so it seems that I cannot move std::discrete_distribution outside the loop. I just want to repeat the code and see the execution time. (i) Using random() and srand() vector<int> res; res.resize(100000000); vector<double> weights{0.1, 0.2, 0.3, 0.4}; srand((unsigned int)time(NULL)); for (int i = 0; i < 100000000; ++i) { double tempSum = 0; double randomNnm = (double)(random()/(double)RAND_MAX); for(int j = 0;j < weights.size(); j++) { tempSum += weights[j]; if(randomNnm <= tempSum) { res[i] = j; break; } } } (ii) Using C++ random library vector<int> res; res.resize(100000000); vector<double> weights{0.1, 0.2, 0.3, 0.4}; for (int i = 0; i < 100000000; ++i) { unsigned seed = chrono::system_clock::now().time_since_epoch().count(); default_random_engine randGen(seed); discrete_distribution<int> thisDistribution(weights.begin(), weights.end()); res[i] = thisDistribution(randGen); // get the final value }
Use the random library correctly. In the C version, you put the call to srand outside of the loop, so do the same in the C++ version for the engine and the distribution. std::vector<int> res(100000000); std::vector<double> weights{0.1, 0.2, 0.3, 0.4}; std::default_random_engine randGen(seed); std::discrete_distribution<int> thisDistribution(weights.begin(), weights.end()); for (int i = 0; i < N; ++i) { res[i] = thisDistribution(randGen); } Demo Timing this code (online, so it might not be accurate), I find the C++ version to be only slightly slower than the C version.
74,336,341
74,336,468
Is std::span constructor missing noexcept?
According to cppreference constructor (2) of std::span is defined as template< class It > explicit(extent != std::dynamic_extent) constexpr span( It first, size_type count ); with its exceptions listed as 2) Throws nothing. If this constructor "throws nothing" then why is it even listed under exceptions and why is the constructor not marked noexcept?
That's because this constructor has preconditions. From the standard: template<class It> constexpr explicit(extent != dynamic_extent) span(It first, size_type count); Constraints: Let U be remove_­reference_­t<iter_­reference_­t>. It satisfies contiguous_­iterator. is_­convertible_­v<U()[], element_­type()[]> is true. [Note 1: The intent is to allow only qualification conversions of the iterator reference type to element_­type. — end note] Preconditions: [first, first + count) is a valid range. It models contiguous_­iterator. If extent is not equal to dynamic_­extent, then count is equal to extent. Effects: Initializes data_­ with to_­address(first) and size_­ with count. Throws: Nothing. Functions with preconditions that "throw nothing" aren't marked noexcept because undefined behavior can occur if these preconditions aren't fulfilled. For example, std::vector::front isn't marked noexcept even though there is no way it would throw, but calling it on an empty vector is undefined behavior. Here is a paper about it: https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2020/p1656r1.html
74,336,813
74,403,298
In vscode tasks.json how to use the g++ to compile-only multiple files and apply the output to make an executable?
What I do want to achieve is separate the compilation and linking steps for multiple .cpp and .h files. Like this: g++ -c *.cpp && g++ -o main *.o. But I would like to do that inside the vscode tasks.json. I tried the following code: Tasks.json { "tasks": [ { "type": "cppbuild", "label": "C/C++: g++ build active file", "command": "/usr/bin/g++", "args": [ "-fdiagnostics-color=always", "-c", "${workspaceFolder}/*.cpp", "&& /usr/bin/g++ -o", "${fileDirname}/${fileBasenameNoExtension} *.o" ], "options": { "cwd": "${fileDirname}" }, "problemMatcher": [ "$gcc" ], "group": { "kind": "build", "isDefault": true }, "detail": "Task generated by Debugger." } ], "version": "2.0.0" } The error I did receive below: Console Starting build... /usr/bin/g++ -fdiagnostics-color=always -c /home/raijin/Documents/Code/Cpp/test/*.cpp "&& /usr/bin/g++ -o" "/home/raijin/Documents/Code/Cpp/test/main *.o" g++: warning: && /usr/bin/g++ -o: linker input file unused because linking not done g++: error: && /usr/bin/g++ -o: linker input file not found: No such file or directory g++: warning: /home/raijin/Documents/Code/Cpp/test/main *.o: linker input file unused because linking not done g++: error: /home/raijin/Documents/Code/Cpp/test/main *.o: linker input file not found: No such file or directory What should I do?
Following the comments suggestion and vscode compound tasks doc. Found a way to compile and produce a executable with the code below: { "tasks": [ { "type": "cppbuild", "label": "c++", "command": "/usr/bin/g++", "args": [ "-fdiagnostics-color=always", "-c", "${workspaceFolder}/*.cpp", ], "options": { "cwd": "${fileDirname}" }, "problemMatcher": [ "$gcc" ], "group": { "kind": "build", "isDefault": false }, "detail": "Task generated by Debugger." }, { "type": "cppbuild", "label": "custom cpp build", "command": "g++", "args": [ "-fdiagnostics-color=always", "-g", "-o", "${fileDirname}/${fileBasenameNoExtension}", "*.o" ], "group": { "kind": "build", "isDefault": true }, "problemMatcher": [ "$gcc" ], "options": { "cwd": "${fileDirname}" }, "dependsOn":["c++"] } ], "version": "2.0.0" } { "tasks": [ { "type": "cppbuild", "label": "c++", "command": "/usr/bin/g++", "args": [ "-fdiagnostics-color=always", "-c", "${workspaceFolder}/*.cpp", ], "options": { "cwd": "${fileDirname}" }, "problemMatcher": [ "$gcc" ], "group": { "kind": "build", "isDefault": false }, "detail": "Task generated by Debugger." }, { "type": "cppbuild", "label": "custom cpp build", "command": "g++", "args": [ "-fdiagnostics-color=always", "-g", "-o", "${fileDirname}/${fileBasenameNoExtension}", "*.o" ], "group": { "kind": "build", "isDefault": true }, "problemMatcher": [ "$gcc" ], "options": { "cwd": "${fileDirname}" }, "dependsOn":["c++"] } ], "version": "2.0.0" } Even so it works, it gets quickly complicated and/or unoptimized as a way to build in c++. I'm going to use cmake as suggested from now on.
74,336,832
74,388,714
authenticate ftp users from sql database in c++
i have a messaging app written in c++ (qt) and now i want to add a library to move heavy media via ftp to a ftp server and give the link to other user to download it. the problem is there are to many users to create separate ftp accounts for all of them manually and using one account for all of them isn't safe.i want to limit every users access to their own subdirectory and delete that dir and ftp account if the users deletes account. i think the following approaches makes sense: 1)in ftp server check login credentials submitted with ftp.login(user,password) in server with existing users in a sql database (users are added to database with signup and deleted with delete account) 2)adding a proxy server to check authorization to access ftp server and then give access to ftp server subdirectory 3)manually writing a ftp daemon for server with c++ or qt library and listen to a port 4)if there is a way to automatically add ftp user to ftp server when signing up if there is another way i'd appreciate the help and if you have an idea how to implement one of the above please explain in detail i tried to find a module in C++ to help build ftp server app but couldn't find any.
i found a way.pureFTPD is a ftp daemon that lets u use a sql database to validate ftp users and limit their access.
74,336,847
74,336,923
Error in the example code of A Tour of C++
I'm going through Mr. Stroustrup's "A Tour of C++" book. In section 9.3 String Views, the author gives the following example: string cat(string_view sv1, string_view sv2) { string res(sv1.length()+sv2.length()); char *p = &res[0]; for (char c : sv1) // one way to copy *p++ = c; copy(sv2.begin(),sv2.end(),p); // another way return res; } When I try to compile this function, I get following error as std::string class doesn't provide any constructor which takes a single int parameter. error: no matching function for call to 'std::__cxx11::basic_string<char>::basic_string(std::basic_string_view<char>::size_type)' 11 | string res(sv1.length()+sv2.length()); I checked the Errata for 2nd printing of A Tour of C++ but there is no mention of this issue. Is this a bug in the example provide or else I'm missing something else?
Is this a bug in the example provide or else I'm missing something else? Yes this is an erratum in the book as std::string doesn't have a constructor that has only one parameter of type int(or convertible to int). Instead it has a constructor std::string::string(size_type, char) that can take a char as the second argument. In particular, from std::string: fill (6) string (size_t n, char c); (6) fill constructor: Fills the string with n consecutive copies of character c. Thus to resolve the erratum, we should pass a second argument as shown below: string res(sv1.length()+sv2.length(), '\0');
74,337,500
74,337,552
is there any way to read one number from the anonymous pipe in two different processes?
I have one anonymous pipe and two child processes. I write one number in the pipe and now i have to read it in both processes. is there any way? I tried to GetStdHandle(STD_INPUT_HANDLE), also I tried to use cin.peek but it doesn't work for me.
You don't tell us which kind of anonymous pipes you're dealing with. However, since pipe is a UNIX concept in its core, I'll assume you're referring to POSIX pipes. These don't support multi-reader access. A read access necessarily consumes the read bytes from the underlying buffer. So what you want is impossible, kind of by design. However, reading that you have two child processes, it would seem sensible to assume you could use shared memory for the actual data exchange, and some other means for synchronization of access.
74,337,532
74,337,695
std::visit does not accept a callable that is a derived class object
I am trying to use std::visit to inspect an std::variant. First I declare the variant and a base (callable) visitor class for the variant: #include <iostream> #include <string> #include <variant> using Amalgamation = std::variant<int, bool, std::string>; class BaseVisitor { public: virtual void operator()(int) {} virtual void operator()(bool) {} virtual void operator()(const std::string&) {} }; Second, I define another visitor class that derives from the base one above: class CheckBooleanVisitor : public BaseVisitor { public: CheckBooleanVisitor() : m_isBoolean(false) { } virtual void operator()(bool) override { // WHERE THE OVERRIDING TAKES PLACE m_isBoolean = true; } bool isBoolean() const { return m_isBoolean; } }; I use this "derived" visitor class to visit a variant like this: int main() { Amalgamation a(0); Amalgamation b(false); CheckBooleanVisitor c; std::visit(c, a); // LINE #1 std::cout << "a is " << (c.isBoolean() ? "" : "not ") << "a boolean." << std::endl; std::visit(c, b); // LINE #2 std::cout << "b is " << (c.isBoolean() ? "" : "not ") << "a boolean." << std::endl; return 0; } And the compiler (VS 2022) complains in LINE #1 and LINE #2 as follows: no instance of function template "std::visit" matches the argument list However, if I try: std::visit((BaseVisitor&)c, a); // LINE #1 std::visit((BaseVisitor&)c, b); // LINE #2 the program outputs as expected: a is not a boolean. b is a boolean. Also, if I give std::visit an instance of BaseVisitor, no errors occur. Why an object of the derived class CheckBooleanVisitor is not accepted as a valid callable for std::visit ? P/s: I'm quite sure the cause of the problem is the code WHERE THE OVERRIDING TAKES PLACE in the definition of CheckBooleanVisitor above. But why ?
Function overloading (multiple functions of the same name in the same scope) and function overriding (a function in a derived class that provides a different implementation from a virtual base class version) interact in unpleasant ways. If a base class defines a function with some name, and a derived class defines a function with that same name, the derived class will by default hide all overloads of the base class version. operator() is not an exception to this rule. Nor is the fact that the base class version is a virtual function that the derived class is overriding. Therefore, if you want the non-overridden versions to be accessible through a derived class instance, you must explicitly using them: virtual void operator()(bool) override { // WHERE THE OVERRIDING TAKES PLACE m_isBoolean = true; } using BaseVisitor::operator();
74,337,618
74,337,669
sort vector by using lambda with &&
I am trying to sort a vector elements by using lambda but I have a question. I am trying to sort it base on 2 values from a struct but lambda does not allow me to do it like that. Here is what i am trying to do: struct Test { int Current; int Max; }; std::vector<Test*> VectorA std::sort(VectorA.begin(), VectorA.end(), [](Test& test, Test& test2) {return (test.Current > test2.Current) && (test.Max > test2.Current); }); Is it possible to use it like that ?
Your std::vector contains elements of type Test*, not Test. Therefore your lambda should accept references to Test* objects, and derefernce the pointers with operator->. Since you do not need to modify these objects, it is better for your lambda to accept the arguments by a const reference. A complete example: #include <vector> #include <algorithm> struct Test { int Current; int Max; }; int main() { std::vector<Test*> VectorA; std::sort(VectorA.begin(), VectorA.end(), //---------------vvvvv--------------vvvvv-------------- [](Test* const& test, Test* const& test2) //----------------------------vv---------------vv----------- { return (test->Current > test2->Current) && (test->Max > test2->Current); }); return 0; } Edit: my answer above addressed only the issue of the c++ syntax itself. As commented below by @Jarod42, there is also a semantic issue here - your comparisson logic does not comply with strict weak ordering (see: Wikipedia - Weak Ordering).
74,337,633
74,337,694
C++ string modification, no pass by reference?
I am a beginner studying C++. Currently I am studying functions, C strings, and pass by reference. The program below is meant to take a string from input, replace any spaces with hyphens, and any exclamation marks with question marks. If the function below, StrSpaceToHyphen() is of return type void, wouldn't the function parameter need to be pass by reference in order for userStr in main() to be modified? The program copied below works as intended. My question is meant to further my understanding of modifying c strings as I was expecting it to behave differently. #include <iostream> #include <cstring> using namespace std; // Function replaces spaces with hyphens void StrSpaceToHyphen(char modString[]) { int i; // Loop index for (i = 0; i < strlen(modString); ++i) { if (modString[i] == ' ') { modString[i] = '-'; } if (modString[i] == '!') { modString[i] = '?'; } } } int main() { const int INPUT_STR_SIZE = 50; // Input C string size char userStr[INPUT_STR_SIZE]; // Input C string from user // Prompt user for input cout << "Enter string with spaces: " << endl; cin.getline(userStr, INPUT_STR_SIZE); // Call function to modify user defined C string StrSpaceToHyphen(userStr); cout << "String with hyphens: " << userStr << endl; return 0; } type here I made the function parameter pass by reference and the program wouldn't compile.
This declaration of the parameter void StrSpaceToHyphen(char & modString[]) { declares an array of references. You may not declare arrays of references. As for your initial declaration void StrSpaceToHyphen(char modString[]) { then the compiler adjusts the parameter having the array type to pointer to the array element type like void StrSpaceToHyphen(char *modString) { As the address of the array is not changed within the function then there is no sense to declare the parameter as a reference to pointer like void StrSpaceToHyphen(char * &modString) { Having the pointer to the first element of the array and the pointer arithmetic you can change any element of the original array. Pay attention to that the variable i and the call of strlen are redundant. You could define the function the following way char * StrSpaceToHyphen( char modString[] ) { for ( char *p = modString; *p; ++p ) { if ( *p == ' ' ) { *p = '-'; } else if ( *p == '!' ) { *p = '?'; } } return modString; }
74,337,792
74,338,338
typedef declaration contains #define directive alias
I use two libraries in my project; let's say A and B for the sake of this question. Unfortunately, I ended up in the following situation: In A.h: #define ssize_t long In B.h: typedef long long ssize_t; This leads to the following error, if A.h is included (i.e., processed) prior to B.h: E0084 invalid combination of type specifiers C2632 '__int64' followed by 'long' is illegal My Question: What is the recommended way to deal with this situation? I could make sure B.h is included prior to A.h instead. I could also #undef ssize_t before including B.h. Neither of which is perfect as it would become my responsibility to ensure the ordering of these includes or uglyfy my code respectively. Update: It's not my code. The first (A.h) seems to be generated from this, the other (B.h) stems from here.
In a pinch, edit both headers, remove configuration logic around the problematic typedef/#define, and insert a simple typedef wrapped in #ifndef in both: #ifndef my_size_t_defined #define my_size_t_defined typedef long long ssize_t; #endif If you are not afraid, you can try creating sys/types.h with these lines in your system includes directory instead (or adding them to your existing sys/types.h, but I gather your system doesn't have one). Configure the libraries again and see if they pick up the definition. A less invasive solution would be to create a non-system directory with sys/types.h and configure both libraries such that they pick up that directory (most build systems have a way of adding custom compiler flags via environment variables).
74,338,102
74,338,163
Class variable gets updated only once in gameloop
I have a problem with updating the value of a class variable on each frame of gameloop. I am using wxWidgets for creating a cross-platform window and for graphics as well as gameloop. This is my main Window class which implements rendering and the gameloop. #include <wx/wx.h> #include "window.h" #include "../entity/entity.h" #include "../../configuration.h" Window::Window(const wxString & title, const wxPoint & position, const wxSize & size): wxFrame(nullptr, wxID_ANY, title, position, size) { timer = new wxTimer(this, 1); Entity entity((width / 2) - 50, 100, 100, 100, wxColour(255, 0, 0)); AddEntity(entity); Connect(wxEVT_PAINT, wxPaintEventHandler(Window::OnPaint)); Connect(wxEVT_TIMER, wxCommandEventHandler(Window::OnTimer)); Start(); } void Window::Render(wxPaintEvent & event) { wxPaintDC dc(this); for (Entity entity : entities) { entity.Render(dc); } } void Window::Update(wxCommandEvent & event) { for (Entity entity : entities) { entity.Update(); } } void Window::AddEntity(Entity & entity) { entities.push_back(entity); } void Window::OnTimer(wxCommandEvent & event) { Update(event); } void Window::OnPaint(wxPaintEvent & event) { Render(event); } void Window::Start() { isStarted = true; timer->Start(10); } void Window::Stop() { isPaused = !isPaused; if (isPaused) { timer->Stop(); } else { timer->Start(10); } } Here is the Entity class which represent a rectangle that can be drawn onto the window. #include <wx/wx.h> #include <stdlib.h> #include "entity.h" #include "../gravity/gravity.h" Entity::Entity(int _x, int _y, int _width, int _height, wxColour _color) : x( _x ), y( _y ), width( _width ), height( _height ), color( _color ) { } void Entity::Render(wxPaintDC & dc) { wxPen pen(color); dc.SetPen(pen); dc.DrawLine(x, y, x + width, y); dc.DrawLine(x, y + height, x + width, y + height); dc.DrawLine(x, y, x, y + height); dc.DrawLine(x + width, y, x + width, y + height); } void Entity::Update() { y += 1; std::cout << y << std::endl; } On each call of the Entity::Update() method, I want to increment the y position and rerender the entity. However, the value of y gets incremented only once and stays the same for the rest of the application lifetime and I can't seem to understand why. I'll be thankful for any help.
When you loop over your entities like this (in Window::Render, Window::Update): for (Entity entity : entities) { in each iteration entity will get a copy of the element in entities. In order to operate on your actual entities via a reference you need to change it to: //----------v--------------------- for (Entity & entity : entities) { Another option is to use auto & (auto by itself does not include "reference-ness" and so will force again a copy as in your code): //---vvvvvv--------------------- for (auto & entity : entities) { Note that even if you only read data from your elements (and don't modify it) you can change your loop to use const & to save the copies.
74,340,185
74,340,222
For loop inside for loop execute only one time
I'm using while loop inside for loop to repeat for loop, but it only execute one time. I did this code: #include<iostream> using namespace std; int h, rep = 0; int main() { cout << "Please enter pyramid's height: "; cin >> h; cout << "Please enter Repetition Number: "; cin >> rep; for(int i = 0; i <= h; i++) { while(0 < rep) { for(int j = 0; j <= h; j++) { if(i >= j) cout << "x "; else cout << " "; } rep--; } cout << endl; } }
while(0<rep){ --rep; } At the conclusion of this while loop rep is 0. This is what the shown code tells your computer to do, so that's what your computer does. Your computer does this because of the Golden Rule Of Computer Programming: "Your computer always does exactly what you tell it to do instead of what you want it do". A corollary to the Golden Rule states: "your computer never does anything you never tell your computer to do". You told your computer to stop the while loop when rep reaches 0, so rep is now 0. rep will still be 0 on the second iteration of the outer loop, so when it gets to this while loop, the second time, rep is still 0. You never told your computer to reset rep to the original value it had before the while loop, so your computer never does that. If you would like for rep to be reset to its original value, every time, you need to tell your computer to do exactly that. It will also be simpler not to even use rep here, but copy its value to a different variable, and have the while loop use and decrement the other variable; so the same thing happens every time.
74,340,375
74,340,530
Why does C++ template argument deduction fail to deduce the elements of a std::array?
The Problem Considering the following (C++20) code #include <array> // class template depends on array of ints template<std::size_t N, std::array<int, N> arr> struct S {}; // fix array length (for convenience) template<int x> using U = S<1, std::array{x}>; // function template depends on array element only template<int x> auto func(U<x>) {} int main() { func(U<2>{}); // error: compiler fails to deduce `x = 2` } godbolt.org Why does the compiler not deduce x = 2 for the call of func? Expectation Since using std::arrays as template arguments is possible and comparison of them is constexpr I am surprised that this does not compile. For any hints regarding why this seemingly simple deduction is not possible for the compilers I would be grateful! Context The following variations do compile but are in my opinion less desirable and I want to avoid them if possible: Variation 1 One variation is to provide an explicit template parameter as in func<2>(U<2>{}) But this is not convenient and leads to repetition. Variation 2 Another possible variation is to carry the explicit template argument around and then restrict the template as in template<std::size_t N, std::array<int, N> arr> auto func(S<N, arr>) requires (N == 1) {} This has the disadvantage to being very verbose.
A non-type template argument containing a template parameter in a subexpression (rather than as the full argument) is a non-deduced context. (See [temp.deduct.type]/5.3.) In other words when deducing the function argument of type S<1, std::array{2}> against the function parameter type S<1, std::array{x}>, then std::array{x} is an undeduced context because x, a template parameter, appears as a subexpression. So std::array{x} can't be used to deduce the template argument for x. The reason for this rule is that it is generally impossible to match std::array{2} against std::array{x}. When the matching is done the compiler doesn't have the expression std::array{2} anymore. It just has an object of type std::array<int, 1> created from that expression and is supposed to figure out which value x needs to be given to the initializer to make an object with the same value (in the structural equality sense used for template argument identity). We know because of how std::array is defined that this requires x to be 2, but in general for other types any argument to the constructor could produce objects of any value. It is impossible to formulate a general rule to perform this matching. I am not exactly sure what your intention with the function is, but if you are just trying to make sure that the function is callable only if N == 1 then template<auto arr> auto func(S<1, arr>) {} will do. Now the non-type template argument to S is the template parameter arr as a whole, not as a subexpression. Now the compiler doesn't have to figure out for which values of arr the expression evaluates to match the value of the corresponding non-type template argument in the function argument. It can just assume that arr is exactly equal to it.
74,340,524
74,340,934
How to read the VAO from the GLSL shader, or pass an Array of indefinite size to the shader?
I partially managed to implement rendering by individual indexes - by loading the indexes into VAO, setting their layout, and passing them using glDrawArrays but now another problem - for test i created arrays in shader itself - ` #version 330 core // Positions/Coordinates layout (location = 0) in int V_Indices; // Colors layout (location = 1) in int T_Indices; // Texture Coordinates layout (location = 2) in int N_Indices; vec3 Vertices[8] = vec3[8]( vec3(- 1.000000, -1.000000, 1.000000), vec3(-1.000000, 1.000000, 1.000000 ), vec3(-1.000000, -1.000000, -1.000000), vec3(-1.000000, 1.000000, -1.000000), vec3( 1.000000, -1.000000, 1.000000), vec3( 1.000000, 1.000000, 1.000000), vec3( 1.000000, -1.000000, -1.000000), vec3( 1.000000, 1.000000, -1.000000)); // vec2 Texcoords[] = vec2[22]( vec2( 0.333333, 0.333333), vec2( 0.666667, 0.000000), vec2( 0.666667, 0.333333), vec2( 0.000000, 0.666667), vec2( 0.333333, 0.333333), vec2( 0.333333, 0.666667), vec2( 0.000000, 0.333333), vec2( 0.333333, 0.000000), vec2( 0.333333, 0.333333), vec2( 0.666667, 0.666667), vec2( 0.333333, 0.666667), vec2( 0.666667, 0.333333), vec2( 1.000000, 0.000000), vec2( 1.000000, 0.333333), vec2( 0.333333, 1.000000), vec2( 0.000000, 0.666667), vec2( 0.333333, 0.666667), vec2( 0.333333, 0.000000), vec2( 0.000000, 0.000000), vec2( 0.666667, 0.333333), vec2( 0.666667, 0.000000), vec2( 0.000000, 1.000000) ); vec3 Normals[] = vec3[6]( vec3(-1.0000, 0.0000, 0.0000), vec3( 0.0000, 0.0000, -1.0000), vec3( 1.0000, 0.0000, 0.00000), vec3( 0.0000, 0.0000, 1.00000), vec3( 0.0000, -1.0000, 0.0000), vec3( 0.0000, 1.0000, 0.0000) ); out vec2 texCoord; uniform mat4 camMatrix; void main() { // Outputs the positions/coordinates of all vertices gl_Position = camMatrix * vec4(Vertices[V_Indices], 1.0); // Assigns the colors from the Vertex Data to "color" // Assigns the texture coordinates from the Vertex Data to "texCoord" texCoord = Texcoords[T_Indices]; } ` But in real conditions, it will not work to make arrays in the shader, moreover, the arrays will be of different lengths The question is - is it possible to load an array of vertices into a VBO and then either get a VBO from a shader - as an array, or somehow read its elements by index If not, then the question is - is it possible to make a dynamic array in the shader, and then pass vertexes to it? - "uniform int ArrSize" "uniform vec3 *arr = new vec3 [ArrSize];
The best fit for this task would be a Shader Storage Buffer Object: layout(std430, binding=0) buffer VertexBuffer { vec3 Vertices[]; }; layout(std430, binding=1) buffer TexcoordBuffer { vec2 Texcoords[]; }; layout(std430, binding=2) buffer NormalBuffer { vec3 Normals[]; }; ... void main() { gl_Position = camMatrix * vec4(Vertices[V_Indices], 1.0); texCoord = Texcoords[T_Indices]; } You'd bind the buffers with: GLuint buffers[] = { vertexBuffer, texcoordBuffer, normalBuffer }; GLintptr offsets[] = { ... }; GLsizeiptr sizes[] = { ... }; glBindBuffersRange(GL_SHADER_STORAGE_BUFFER, 0, 3, buffers, offsets, sizes); Although the layout of SSBOs is less flexible than VAOs, they do allow indexing very big buffers (usually as big as you can allocate). However, SSBOs were introduced in OpenGL 4.3, and may only be available on earlier versions through an extension. If you'd like it to work with earlier OpenGL versions, you may look at Uniform Buffer Objects or Buffer Textures.
74,340,726
74,340,741
Why does my deposit feature only let me deposit 10,000 or less?
I created a bank app, and when I try to deposit money that is over 10,000, my error message that I set up displays, but any number under works.. I assume this has something to do with value types. I used int, however I tried double but can't figure that out too. /* FUNCTION DEFINITION */ void DepositMoney(int initialbalance, int deposit); // Main Program int main() { int initialbalance=10000; int deposit; cout << " \t ***** What you want to Do ??? Choose the Action character *****" << endl << endl; cout <<" \t W : Money Withdraw" << endl <<"\t D : Deposit" << endl //I CHOSE THIS ONE <<"\t B : Balance" << endl <<"\t T : Transfer" << endl <<"\t C : Change Details" << endl <<"\t Q : Quit or Exit" << endl << endl ; string input; cin >> input; bool t=true; if (input=="W" || input=="w"){ cout<<"\n\t Your balance is: " << initialbalance<<endl; cout<<"\n\t How much would you like to withdraw: "; cin>> withdraw; withdrawMoney(initialbalance, withdraw); initialbalance -= withdraw; t=false; } else if (input=="D" || input=="d"){ cout<<"\n\t Your balance is: " << initialbalance<<endl; cout<<"\n\t How much would you like to deposit: "; cin>>deposit; DepositMoney(initialbalance, deposit); initialbalance += deposit; t=false; // Function for Deposit void DepositMoney(int initialbalance, int deposit) { // Get how much user want to deposit and display balance after adding if(initialbalance < deposit) cout <<"\n\t The amount you entered is not not valid."<<endl; //THIS MSG DISPLAYS else initialbalance += deposit; cout<<"\n\t Your new balance is: " << initialbalance <<endl<<endl<<endl; } I tried changing every data type that said int to double, but that didn't even run the code.
When you call DepositMoney(), you have this check: if (initialbalance < deposit). At this point, initialbalance is 10000, so if the amount is greater, then you cannot deposit it. Based on the logic, you likely wanted a check like that in withdrawMoney(), not in DepositMoney().
74,340,753
74,340,921
getting '0b' in memory when trying to serialize object in c++
I am trying to serialize an object for sending in a socket, but for some reason, when i add to the string stream using <<, I'm also adding '0b' after it, i've tried looking for something that may cause this (such as a fault data type) but so far i came up with nothing. this is my object before in memory before the serialization - 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 03 0b 00 cc ff 00 00 00 this is the memory of the ostream that i use for the serialization - 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 03 0b 03 0b 00 ff 00 00 00 this is the class itself and the overloading for serialization ` std::ostream& operator << (std::ostream& os, Header H) { os << H.CID; os << H.Version; os << H.FirstTwoCode; os << H.LastTwoCode; os.write(reinterpret_cast<const char*>(&H.Payload_size), sizeof(int)); return os; } class Header { UINT8 CID[CLIENTID_BYTE_SIZE]; unsigned char Version; unsigned char FirstTwoCode; unsigned char LastTwoCode; int Payload_size ; } Header::Header(UINT8 clientID[CLIENTID_BYTE_SIZE], int request_code, int PL_SIZE) { memcpy(CID, clientID, CLIENTID_BYTE_SIZE); Version = char(VERSION_NUMBER); FirstTwoCode = char(request_code / 100); LastTwoCode = char(request_code % 100); Payload_size = PL_SIZE; } ` I've tried searching the web, and gone over my a lot of times, i think that it may have something to do with me saving integers inside chars, and the casting is doing something, but I'm not sure.
Your bug is in this line: os << H.CID; It calls the unsigned char overload of (2) here: https://en.cppreference.com/w/cpp/io/basic_ostream/operator_ltlt2, which means it just writes the memory of your Header object until the first null byte. To achieve what you actually wanted, you can do something like os.write(reinterpret_cast<char const*>(H.CID), CLIENTID_BYTE_SIZE);
74,340,846
74,340,868
What does it mean by member initialization list initializing an attribute of a class
If I have a class like the below one: class foo { private: int a; public: foo (int arg1) : a(arg1) {} }; The attribute a will be default-initialized in the line it got declared. Now, when the parameterized constructor is called, it gets re-initialized to the value arg1 in the member-initialization list. Is my understanding correct that a gets re-initialized in the member initialization list? If yes, what does it mean by an attribute getting re-initialized (Initialization means memory getting allocated. Now, what does re-initialization mean?)?
No, a won't be "re-initialized", i.e. initialized twice. When the parameterized constructor is used a will only be direct-initialized from the constructor parameter arg1, no default-initialization happens. If foo has another constructor which doesn't initialize a in member-init-list, then it'll be default-initialized. E.g. class foo { private: int a; public: foo (int arg1) : a(arg1) {} // a is direct-initialized from arg1 when this constructor used foo () {} // a is default-initialized when this constructor used };
74,341,308
74,350,257
How do I write a function signature such that it will take in a container or a range?
I was trying to make a single function that takes in a container and implicitly have it convert to a boost::iterator_range as I thought that was it's purpose, but it seems that I'm missing something. Here's an example of what I was thinking: #include <boost/range/iterator_range.hpp> #include <vector> template<typename IT> void fn_x(boost::iterator_range<IT>) { } void fn_y() { std::vector<int> a(64); fn_x(boost::make_iterator_range(a.begin(), a.end())); // Works fn_x(a); // Doesn't } Demo So how would I get fn_x to accept both a container and a range object, in the same function? Sorry, forgot to mention that I'm using c++14.
The "obvious" answer is to be less specific: Live On Coliru #include <boost/range/iterator_range.hpp> #include <iostream> #include <numeric> #include <vector> template <typename Range> auto fn_x(Range&& r) { using std::begin; using std::end; return accumulate(begin(r), end(r), 0.0); } int main() { std::vector<int> a{1,2,3}; std::cout << fn_x(boost::make_iterator_range(a.begin(), a.end())) << "\n"; std::cout << fn_x(a) << "\n"; } Prints 6 two times. If you really want to be more specific consider: std::span (c++20) - which has implicit conversions from e.g. std::vector range concepts (c++20) if all else fails, sfinae: template <typename It> auto fn_x(boost::iterator_range<It> r) { return accumulate(r.begin(), r.end(), 0.0); } template <typename SomeOtherRange, typename Enable = decltype(boost::make_iterator_range(std::begin(std::declval<SomeOtherRange>()), std::end(std::declval<SomeOtherRange>())))> auto fn_x(SomeOtherRange const& r) { return fn_x(boost::make_iterator_range(std::begin(r), std::end(r))); } See it Live On Coliru (c++11 compatible) #include <boost/range/iterator_range.hpp> #include <iostream> #include <numeric> #include <vector> template <typename It> double fn_x(boost::iterator_range<It> r) { return accumulate(r.begin(), r.end(), 0.0); } template <typename SomeOtherRange, typename Enable = decltype(boost::make_iterator_range(std::begin(std::declval<SomeOtherRange>()), std::end(std::declval<SomeOtherRange>())))> double fn_x(SomeOtherRange const& r) { return fn_x(boost::make_iterator_range(std::begin(r), std::end(r))); } int main() { std::vector<int> a{1, 2, 3}; std::cout << fn_x(boost::make_iterator_range(a.begin(), a.end())) << "\n"; std::cout << fn_x(a) << "\n"; } Still printing 6 6
74,341,356
74,341,416
I can't select a different option in my program
I was writing a program inspired by one of my favorite books Diary of a wimpy kid. You play as Greg's dad and you have 3 options with what to do with him. When i ran the program I first selected the first option which printed the first one. I tried it again with the third option as well with the same result. #include <iostream> using namespace std; void greg(int choice){ cout<<"Option 1: Scold."<<endl; cout<<"Option 2: Take away games."<<endl; cout<<"Option 3: kill "<<endl; cin>>choice; //Options on what to do with greg and getting user input. if(choice = '1'){ cout<<"You told Greg he sucks. Responds with:"<<endl; cout<<"Ok.."<<endl; } else if(choice = '2'){ cout<<"You storm into Greg's room while Greg keeps asking you why."<<endl; cout<<"Once you are insde and grab his game."<<endl; }else if(choice = '3'){ cout<<"you killed greg."<<endl; cout<<"A white bang then proceeds to happen."<<endl; cout<<"You killed the main character. You no longer exist."<<endl; }else{ cout<<"no"<<endl; } } //All above is what will happen if you pick a choice. int main() { cout<<"There once was a guy named Frank."<<endl; cout<<"You talk to greg."<<endl; cout<<"Yeah dad?"<<endl; greg(3); return 0; }
you have to use a double = because you want to compare the values in the if statement. You dont want to set the left variable equal to the right value. 2.because youre passing a int value into the function, the program will not return true because a int is not equal to a string. So you dont have to use these '' around the number. In conclusion you have to change this: ... if(choice == 1){ //your code } else if(choice == 2){ //your code } else if(choice == 3){ //your code } ...
74,341,491
74,341,956
Rust: Default structure member initialization for static structures?
I'm evaluating Rust as a possible replacement for C/C++ in a new iteration of embedded FW. As I create simple projects, potential inconveniences come up. It's important for this application that migration be relatively painless, meaning that the most idiomatic Rust approach to a design pattern may not be possible. But it is also valuable to learn those idioms, so I'd like to learn. With that background .... In C++, it is easy to create default values for structures and allocate statically. struct foo { int bar = 3; float baz = 10.0; char* msg = "hello there"; } foo my_foo; However, in Rust, getting default values for structure members seems to require using the Default::default() functionality. Consider this similar try: struct MyStruct { a: i32, b: f32, c: bool, } impl Default for MyStruct { fn default() -> MyStruct { MyStruct { a: 3, b: 4.0, c: true, } } } static FOO: MyStruct = MyStruct { a:1, ..Default::default() }; So not only do I have to write a completely separate piece of code to create the defaults, but static allocation doesn't seem to be supported: error[E0015]: cannot call non-const fn `<MyStruct as Default>::default` in statics --> src/main.rs:92:42 | 92 | static FOO: MyStruct = MyStruct { a:1, ..Default::default() }; | ^^^^^^^^^^^^^^^^^^ | = note: calls in statics are limited to constant functions, tuple structs and tuple variants This all seems very awkward compared to C++. I understand the idioms may be different, but relatively straightforward migration from C++ is important in this application - more appropriate Rust idioms can be brought in over time. And also, having to write more code to accomplish what was done previously is not likely to go over well. Is there another approach to this problem?
The sticking point that you've hit is that static intializers must be const expressions but traits (like Default) do not have const support (yet). You'll need to implement a const function to construct your MyStruct without using Default: impl MyStruct { pub const fn new() -> MyStruct { MyStruct { a: 3, b: 4.0, c: true, } } } static FOO: MyStruct = MyStruct { a:1, ..MyStruct::new() }; Or if this is common, you may want a dedicated constructor for it: impl MyStruct { pub const fn with_a(a: i32) -> MyStruct { MyStruct { a, b: 4.0, c: true, } } } static FOO: MyStruct = MyStruct::with_a(1);
74,341,693
74,342,421
set::set from variadic template arguments
How do I create a set from arguments of variadic templated function? template<class T> concept Int = std::same_as<T, int>; template<Int... Ints> std::set<int> fun (Ints... ints) { // create and return a set containing arguments to this function }
You can expand the pack using pack expansion as shown below: template<Int... Ints> std::set<int> fun (Ints... ints) { return {ints...}; //use unary right fold } int main() { std::set<int> myset = fun(1,2,3); } Demo
74,342,032
74,342,494
C++ Cannot list files of dir C:\Users\User\Recent\
I'm trying to create an application that will delete specific files from C:\Users\User\Recent. For this I want to go through all the files first and see if the file should be deleted. I've tried many things, for example: const char* path2 = "C:\\Users\\User\\Recent\\"; for (const auto& dirEntry : std::filesystem::recursive_directory_iterator(path2)) { std::cout << dirEntry << std::endl; std::cout << "x" << std::endl; } This just doesn't print anything, and when i try to open the dir with opendir from the dirent.h library it just returns NULL const char* path2 = "C:\\Users\\User\\Recent\\"; DIR *dr; dr = opendir(path2); // dr = NULL Everything else i tried gave me similar results.
Call SHGetFolderPath to get the correct location of the Recent folder. It is usually somewhere inside %AppData%. If you wish to "clean" this folder correctly, accessing it directly from the file system is not ideal because there is mirrored information stored in the registry (HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\RecentDocs). To properly deal with this you should call SHCreateItemFromParsingName on the file you want to delete and on the shell item, bind with BHID_SFUIObject to get IContextMenu and invoke the delete verb. Or better yet, use SHGetKnownFolderItem and never look at the file system...
74,342,218
74,356,014
Will std::make_unique<alignas(32) std::byte[]> allocate aligned memory?
I'm wondering if I can replace code like std::unique_ptr<std::byte[]> p { new (std::align_val_t{32}) std::byte[size]{} }; with auto p = std::make_unique<alignas(32) std::byte[]>(size);
Well, the first problem is that there is no such type as alignas(32) std::byte[]. It is not a valid type-id. You can see the grammar for type-id here. To make alignas(32) apply to std::byte[], you would have to put it at the end: std::byte[] alignas(32). This is grammatically correct, but it has no effect. In other words, std::byte[] alignas(32) is the same type as std::byte[]. As such, std::make_unique<std::byte[] alignas(32)> is the same as std::make_unique<std::byte[]> It will not align the allocated memory to a 32-byte boundary. This is a common source of confusion, so I will elaborate a bit. Consider the following: alignas(16) char c; The variable (or non-static data member) c will be aligned to a 16-byte boundary. But why? It is natural to think that alignas(16) char is the type of c, and that since this type has an alignment of 16, the variable has an alignment of 16. But it's not so. alignas(16) should be thought of as being more like extern or inline. It applies to the variable, not the type. The type of c is char, and the alignment of c is 16. Alignment is just not part of the type system (though, of course, every complete type has an alignment).
74,343,214
74,343,533
Big O notation of Formula - P *R Squared
I want to calcuate the Big O notation for an area of circle.I wonder what is the time complexity of Pi *r^2? is it O(n) or O(n^2)? Please also check if my way of doing is correct. Algorithm Step 1: Start // f(n)=O(1) ( Executes 1 time) Step 2: Get an integer input from user for AREA and RADIUS//. f(n)=O(n)=O(1) ( Executes 1 time) Step 3: Print the statement "Enter the Radius of Circle: //f(n)=O(n)=O(1) ( Executes 1 time) Step 4: Calculate the area of the circle using the formula of //f(n)=O(n)=? (r - Radius) //f(n)=O(n)=O(1) ( Executes 1 time) Step 5: Print the statement "Area of Circle:" //f(n)=O(n)=O(1) ( Executes 1 time) Step 6: Print Area//f(n)=O(n)=O(1) ( Executes 1 time) Step 7: Stop //f(n)=O(n)=O(1) ( Executes 1 time) f(n)=O(n)=?
This depends on your model of computation. For most practical purposes its O(1), because the runtime does not depend on your input r. This assumes implicitly that your input is bounded, for example fits into a 32-bit integer. More theoretical you can think about arbitrary big r. The N in the big O notation then is normally the length (number of bits) of r and not the size of the number. Here you cant assume that you can multiply any two numbers in O(1) but it will depend on the length of the numbers. In this case you would get O(N^2) with a naive multiplying algorithm, which can be improved to O(N log N) with more advanced techniques. See https://en.wikipedia.org/wiki/Multiplication_algorithm#Computational_complexity_of_multiplication .
74,343,255
74,343,891
How to efficiently perform a list of transformations in place on an object in C++?
I'm new to C++ and am a bit confused by how references, values, and move semantics work. I want to implement a function that can take an event, apply a list of transforms, and output the transformed event. Here's a code snippet: std::vector<Event (*)(Event)> transforms = ...; Event process(Event baseEvent) { Event&& e = std::move(baseEvent); for(auto fn: this->transforms) { e = fn(e); } return e; } The requirements: The baseEvent should not be modified in place by process. I believe this is achieved here since I am passing the event in by value. The process method's copy of baseEvent should be modified in place by each transform. I want to be careful not to make any extra copies. Each transform function takes in the event as an rvalue reference. However, I'm not sure if this is being achieved. I read up on move semantics and tried to reason through the code, but not sure if the requirements are being met.
Your transformation function takes an Event and returns a new Event. It is literally impossible to build a "should modify in place" function on top of that. So your function is already pretty much as close as you can get to what you want, except for the rvalue reference thing. There's no point in doing that. You want to std::move into the function, so that the argument can be move-constructed, but otherwise just assign back to the one object you already have. Event process(Event e) { for(auto fn: this->transforms) { e = fn(std::move(e)); } return e; } If you want the transformation functions to actually modify in place, you need to give them the ability to do so: std::vector<void (*)(Event&)> transforms = ...; Event process(Event e) { for(auto fn: this->transforms) { fn(e); } return e; }
74,343,922
74,343,997
E0298 inherited member is not allowed
I am trying to program chess. I want create is virtual parent class Tool, and child classes for each peace type. Here is my 4 files I writed: Tool.h #pragma once #include <iostream> using namespace std; class Tool { protected: string type; int row; int colum; int player; public: Tool(int row, int col, int player = 0); string getType(); int getRow(); int getColum(); int getPlayer(); bool isLegitimateMove(int row, int col); void move(int row, int col); }; Tool.cpp #include "Tool.h" Tool::Tool(int x, int y , int p) : type("") { row = x; colum = y; player = p; } int Tool::getColum() { return colum; } int Tool::getRow() { return row; } int Tool::getPlayer() { return player; } string Tool::getType() { return type; } void Tool::move(int newRow, int newColum) { row = newRow; colum = newColum; } King.h #pragma once #include "Tool.h" class King : public Tool { }; King.cpp #include "King.h" #include <cstdlib> bool King::isLegitimateMove(int a, int b) { return (abs(a - row) <= 1) and (abs(b - colum) <= 1); } But the VS don't give King to inherit from Tool and write the next errors: E0298 inherited member is not allowed (King.cpp Line 4) C2509 'isLegitimateMove': member function not declared in 'King' (King.cpp Line 4) Can you help me fix this code? I have tyried read this manuals https://www.geeksforgeeks.org/inheritance-in-c/ but it didn't help me.
The problem is that in order to provide an out of class definition for a member function of a class, a declaration for that member function must be present inside the class. And since there is no such declaration inside the derived class King, we can't define it that way you did. Thus to solve this add a declaration for the member function inside the derived class King: class King : public Tool { bool isLegitimateMove(int row, int col); //declaration added }; Also you might want to make isLegitimateMove a virtual member function by adding the keyword virtual when declaring it in the base class.
74,344,328
74,344,970
How to check if a key is empty in map<int,pair<int,int>> - C++ STL
I have a unordered_map<int, vector<pair<int, int> > > revert; How do I check if some key is not present in the map If I apply revert[id].size()==0 condition , its be default size is some big number 107374182. How do I check if its empty?? I tried to add breakpoint and debug , and that is where I found that its default size is a very big number and the condition is failing. Could you please help me with this? Thanks a lot
revert[id].size()==0 will access the size() function a newly created std::vector if nothing was inserted with key id before. I'm not sure why the size is this big random number here and I have no way to check without a full example. To correctly check if an entry with key id exists in revert you can use revert.conains(id) (documentation) if you are using C++-20, or revert.find(id) != revert.end() (documentation) otherwise.
74,344,350
74,348,380
char8_t and utf8everywhere: How to convert to const char* APIs without invoking undefined behaviour?
As this question is some years old Is C++20 'char8_t' the same as our old 'char'? I would like to know, what is the recommended way to handle the char8_t and char conversion right now? boost::nowide (1.80.0) doesn´t not yet understand char8_t nor (AFAIK) boost::locale. As Tom Honermann noted that reinterpret_cast<const char *>(u8"text"); // Ok. reinterpret_cast<const char8_t*>("text"); // Undefined behavior. So: How do i interact with APIs that just accept const char* or const wchar_t* (think Win32 API) if my application "default" string type is std::u8string? The recommendation seems to be https://utf8everywhere.org/. If i got a std::u8string and convert to std::string by std::u8string convert(std::string str) { return std::u8string(reinterpret_cast<const char8_t*>(str.data()), str.size()); } std::string convert(std::u8string str) { return std::string(reinterpret_cast<const char_t*>(str.data()), str.size()); } This would invoke the same UB that Tom Honermann mentioned. This would be used when i talk to Win32 API or any other API that wants some const char* or gives some const char* back. I could go all conversions through boost::nowide but in the end i get a const char* back from boost::nowide::narrow() that i need to cast. Is the current recommendation to just stay at char and ignore char8_t?
This would invoke the same UB that Tom Honermann mentioned. As pointed out in the post you referred to, UB only happens when you cast from a char* to a char8_t*. The other direction is fine. If you are given a char* which is encoded in UTF-8 (and you care to avoid the UB of just doing the cast for some reason), you can use std::transform to convert the chars to char8_ts by converting the characters: std::u8string convert(std::string str) { std::u8string ret(str.size()); std::ranges::transform(str, ret.begin(), [](char c) {return char8_t(c);}); return ret; } C++23's ranges::to will make using a named return variable unnecessary. For dealing with wchar_t interfaces (which you shouldn't have to, since nowadays UTF-8 support exists through narrow character interfaces on Windows), you'll have to do an actual UTF-8->UTF-16 conversion. Which you would have had to do anyway.
74,344,876
74,345,197
C++ SIGABRT on new thread
I'm trying to parallelize a method inside a Parser class. Since this method requires shared mutex I wasn't able to use OpenMP, and therefore had to go with the standard libraries. I'm currently working with C++ 17, and here's the main code that's not working: auto p = Parser(.7); int tMax = thread::hardware_concurrency(); vector<thread> threads; int chunk = (int)lines.size() / tMax; for (int i = 0; i < tMax; ++i) { int start = chunk * i; threads.emplace_back(&Parser::parse, &p,lines, start, i); } The problem is that I get a SIGABRT at the creation of a new thread and I can't figure out the reason for this. You can find the full/messy code here. In case you want to dive into it I'll leave a brief list of the important lines: 32-110: Auxiliary objects definitions 112: Start of Parser definition 335: parse method definition 424: main (referenced code at 443) I looked for similar cases to mine (like this one) but I still can't understand what is really happening and why. Debugging only leads me to the thread constructor and into assembly code, until it reaches the terminate exception thrower. I think I might be messing something up with address and references, since I'm passing the object itself, but I don't have enough experience with C++ to know for certain. I should also mention that this function works perfectly when called within the main thread, but when creating the second thread it seems to throw SIGABRT. EDIT: Minimal/Cleaned Example can be found here.
You're creating a vector of threads and then immediately exit main without waiting for any of them to finish execution. This will cause them to crash. Adding for(auto& t : threads) t.join(); to the end of main to wait on all the threads works in my test.
74,345,380
74,345,470
c++ Friend function not recognised as friend with template specialisation
I am trying to declare a function as friend to a class template with a protected member. Below is a minimal example. template<int N> class myClass{ public: friend void f(const myClass& c); protected: int a; }; If I now define the function as template<int N> void f(const myClass<N>& c){ std::cout << c.a; }; Then it works. However if I use template specialisation template<int N> void f(const myClass<N>& c); template<> void f<1>(const myClass<1>& c){ std::cout << c.a; }; It does not recognise f as a friend anymore and complains that a is a protected member. Why is that happening? What am I doing wrong?
The problem is that the friend declaration friend void f(const myClass& c); is a nontemplate friend declaration. That is, you're actually befriending a nontemplae free function. This is exactly what the warning tells you: warning: friend declaration 'void f(const myClass<N>&)' declares a non-template function [-Wnon-template-friend] 12 | friend void f(const myClass& c); To solve this you need to add a separate parameter clause for the friend declaration as shown below: template<int N> class myClass{ public: template<int M> //added this parameter clause friend void f(const myClass<M>& c); protected: int a; }; Working demo
74,345,808
74,345,895
How to print the current filename with a function defined in another file without using macros?
Is it possible to print the caller source file name calling a function defined in another file, without passing __FILE__ explicitly and without using preprocessor tricks? // Header.h #include <iostream> #include <string> using namespace std; void Log1(string msg) { cout << __FILE__ << msg << endl; // this prints "Header.h" } void Log2(string file, string msg) { cout << file << msg << endl; } inline void Log3(string msg) { cout << __FILE__ << msg << endl; // this prints "Header.h" } // Source.cpp #include "Header.h" int main() { Log1(" Test 1"); Log2(__FILE__, " Test 2"); Log3(" Test 3"); } With this code, this is what I get: pathTo\Header.h Test 1 pathTo\Source.cpp Test 2 pathTo\Header.h Test 3 I would have expected the last call to print: pathTo\Source.cpp Test 3
You could use std::source_location: // library.h #pragma once #include <source_location> #include <string> void Log(std::string msg, const std::source_location loc = std::source_location::current()); // library.cpp #include "library.h" #include <iostream> void Log(std::string msg, const std::source_location loc) { std::cout << loc.file_name() << ' '<< msg << '\n'; } // Source.cpp #include "library.h" int main() { Log("Test 1"); // Prints "Source.cpp Test 1" } This requires C++20. Prior to C++20 you can use boost::source_location.
74,346,000
74,346,788
C++ prevent ambiguous parameter int vs int&
I specalized QApplication as MyApplication taking an int parameter for construction. class MyApplication : public QApplication { public: Foo( int argc, char **argv ) : QApplication( argc, argv ) { ... } }; This class is again specialized in many places in my code. Unfortunately, I used int, while I should have used int& (as Qapplication expects). Under Windows it did not cause any trouble, but when I moved to Linux it started crashing. So I changed MyApplication to: class MyApplication : public QApplication { public: Foo( int& argc, char **argv ) : QApplication( argc, argv ) { ... } }; But then, all classes specializing MyApplication also need to be updated, and there are many of them, if they are not, code still compiles but is likely to crash. I need to identify all places where the change should be applied, but I also want to prevent new code from doing the same mistake. Is there any way/trick to prevent specialization with int instead of `int&' to compile? I'd like this code not to be permitted and to produce compilation error: class OtherApplication : public MyApplication { public: Foo( int argc, char **argv ) : MyApplication( argc, argv ) { ... } };
One approach is to wrap the parameters in your own structure and pass that. This forces subclass construction to use that signature. It also allows more flexibility if for whatever reason you ever want to add additional stuff to the constructor without going and modifying everything. This technique is used in some APIs to avoid breaking function signatures with minor changes. I've shown this inline for simplicity, but you could of course hide the implementation if you want. class MyApplication : public QApplication { public: struct Args final { Args(int& argc, char** argv) : argc(argc) , argv(argv) {} int& argc; char** argv; }; MyApplication(const Args& args) : QApplication(args.argc, args.argv) { } }; int main(int argc, char** argv) { MyApplication myapp({argc, argv}); // ... }
74,346,252
74,564,620
How to setup {fmt} library for Unreal Engine project?
I'm trying to setup fmt for UE4 project, but still getting compiler errors. Used toolchain: MSVC\14.16.27023 fmt lib is build from source. I googled this issue and undefined check macro. #undef check #include <fmt/format.h> void test() { auto test = fmt::format("Number is {}", 42); } Getting this compiler errors: I tried this defines and this still not compile. #define FMT_USE_CONSTEXPR 0 #define FMT_HEADER_ONLY Maybe someone managed use fmt library in Unreal Engine projects and can share some experience?
There is two main problem with integrating {fmt} library in Unreal Engine. global define for check macro. Some variables/function inside fmt implementation named "check". So there is a conflict. Warning as errors enabled by default. So you have either disable this, or suppress specific warnings. I ended up with this solution for my UE project. I difined my own header-wrapper MyProjectFmt.h #pragma once #define FMT_HEADER_ONLY #pragma push_macro("check") // memorize current check macro #undef check // workaround to compile fmt library with UE's global check macros #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable : 4583) #pragma warning(disable : 4582) #include "ThirdParty/fmt/Public/fmt/format.h" #include "ThirdParty/fmt/Public/fmt/xchar.h" // wchar support #pragma warning(pop) #else #include "ThirdParty/fmt/Public/fmt/format.h" #include "ThirdParty/fmt/Public/fmt/xchar.h" // wchar support #endif #pragma pop_macro("check") // restore check macro And then use it in your project like this: SomeActor.cpp #include "MyProjectFmt.h" void SomeActor::BeginPlay() { std::string TestOne = fmt::format("Number is {}", 42); std::wstring TestTwo = fmt::format(L"Number is {}", 42); } Also, you could create some Macro-wrapper around it to putt all your characters in Unreal Engine's TEXT() macro, or even write custom back_inserter to format characters directly to FString. This is easy to implement, but this is another story.
74,346,596
74,346,619
How do i solve this "chicken vs egg" declaration issue?
New with C++ but been coding a lot of ObjC back in the day. So i thought i was smart trying to solve a cross reference issue with the old delegate pattern used widely in ObjC but only managed to move the issue it to another file . Im trying to reach the invoker of the file by passing it as a reference, conforming to a "interface". #pragma once #include <libUI.h> #include <Arduino.h> class PeripheralDelegate { public: virtual void pushViewController(PeripheralViewController* vc) = 0; virtual void popLastViewController() = 0; }; class PeripheralViewController: public ViewController { private: PeripheralDelegate* mDelegate; public: PeripheralViewController(): ViewController(), mDelegate() {} PeripheralViewController(String id, Rect frame, PeripheralDelegate* delegate): ViewController(id, frame), mDelegate(delegate) {} virtual ~PeripheralViewController() {} virtual void encoderValueChanged(int newVal, int oldVal) = 0; virtual void encoderSwitchPressed() = 0; virtual void backButtonPressed() = 0; virtual void firstButtonPressed() = 0; virtual void secondButtonPressed() = 0; }; Also, all kind of feedback on the code is much appriciated!
You can predeclare PeripheralViewController and then you can use a pointer to it: class PeripheralViewController;
74,346,902
74,347,083
Enter an If Statement Using Probabilities
I have the function mutateSequence that takes in three parameters. The parameter p is a value between 0 and 1, inclusive. I need two if statements, one that is entered with probability 4p/5 and another that is entered with probability p/5. How do I write the logic to make this happen? Code: void mutateSequence(vector<pair<string, string>> v, int k, double p) { for (int i = 0; i < k - 1; i++) { string subjectSequence = v[i].second; for (int j = 0; j < subjectSequence.length(); j++) { // with probability 4p/5 replace the nucelotide randomly if (//enter with probability of 4p/5) { //do something } if (//enter with probability of p/5) { //do something } } } } I am expecting that the first if statement is entered with probability 4p/5 and the second if statement is entered with probability p/5
There's a very straightforward way to do this in modern C++. First we set it up: #include <random> std::random_device rd; std::mt19937 gen(rd()); // p entered by user elsewhere // give "true" 4p/5 of the time std::bernoulli_distribution d1(4.0*p/5.0); // give "true" 1p/5 of the time std::bernoulli_distribution d2(1.0*p/5.0); Then when we want to use it: if (d1(gen)) { // replace nucleotide with 4p/5 probability } else { // something else with 1 - 4p/5 probability } If instead, you want do one thing with probability 4p/5 and then, independently, another thing with probability 1p/5, that's also easily done: if (d1(gen)) { // replace nucleotide with 4p/5 probability } if (d2(gen)) { // something else with 1p/5 probability } See bernoulli_distribution for more detail.
74,347,061
74,347,269
C++ read multiple optional inputs from std::cin
While trying to generate a simpleVM for learning C++, I faced following Problem: So lets assume I want and Input of 10 C 222, where 10 would be the opcode (movi in this case), C a register and 222 a value. Thus 10 C 222 would store 222 into register C. To get some Input, I am currently using int runVM(){ int i, v; //opcode i, Value v char n; //Register while (true) { std::cin >> i >> n >> v; switch (i) { case 0: return C; case ... } However, this only allows me to enter 3 inputs. Not less. With the opcode of 0, my VM would close and return C, so no input Register or Value is needed. Currently I still need to enter 0 0 0 to return and break the loop. Is there any function in C++ that allows me to expect 1, 2 or 3 ińputs and uses a default (empty value) when simply pressing enter?
One choice is to read the opcode and then decide what else needs to be done. This looks like int runVM(){ int i, v; //opcode i, Value v char n; //Register int C = 1; // undefined in OP while (true) { std::cin >> i; switch (i) { case 0: return C; case 10: std::cin >> n >> v; // do something break; // ... } // ... } }
74,347,125
74,347,201
operator overloading() for a user-defined type in unordered_map
I was looking at this post C++ unordered_map using a custom class type as the key I understand that we need to redefine equality and hash code for a custom type key. I know how the operator overloading works in general. However, what does operator() have to do with the hash code? Does unordered_map internally evaluate a key with () operator somewhere?
The std::unordered_map uses an std::hash object to calculate the hash-values. It will use the hash-object like a function, calling the operator() to do the calculation. As a simple example, for an int key, it will be something like this: int key = 123; // Or whatever value... std::hash<int> hash_object; auto hash_value = hash_object(key); // Calls hash_object.operator()(key)
74,347,904
74,348,013
How to get compiler to deduce parameters for function with `concept auto...` given initializer lists
I am trying to get the hang of C++20 concepts. I want to define a function taking an arbitrary number of Foo instances and have the compiler implicitly convert input arguments to Foo instances. The problem is that the implicit conversion does not seem to work if I use initializer_lists. The last line in the following code is the offending one. Is this possible with concepts and C++20? If yes, how should I change my code? If no, is there any other way to let the compiler to automatically do the implicit conversion? #include <iostream> #include <concepts> struct Foo { Foo(){ std::cout << "No argument!\n"; } Foo(int){ std::cout << "One argument!\n"; } Foo(int, int){ std::cout << "Two arguments!\n"; } }; // function takes a single Foo void foo(Foo foo){} // function takes any number of Foos template <typename... Foos> requires (std::is_convertible_v<Foos, Foo> && ...) void foos(Foos... foos){} int main() { // converting ctors work Foo x = 42; Foo y = {42, 42}; Foo z = {}; std::cout << "\n"; // argument deduction works for foo foo(42); foo({42, 42}); foo({}); std::cout << "\n"; // argument deduction works for foos using only second ctor foos(1, 2, 3); std::cout << "\n"; // argument deduction does not work for foos if we use initializer lists foos(42, {42, 42}, {}); } GCC complains: error: too many arguments to function 'void foos(Foos ...) [with Foos = {}]' MSVC complains: 'initializer list': is not a valid template argument for 'Foos' Clang complains: candidate template ignored: substitution failure: deduced incomplete pack <int, (no value), (no value)> for template parameter 'Foos' Godbolt link
{..} has no types, and can only be deduced as std::ininitilizer_list<T> or T[N]. As alternative, you might use void foos(std::initializer_list<Foo> foos){/**/} with call similar to: foos({42, {42, 42}, {}});
74,348,000
74,348,127
cannot bind non-const lvalue reference of type 'int*&' to an rvalue of type 'int*'
I am aware that there are some questions similar to this one but I am a beginner in c++ and those examples were a bit difficult to comprehend for me. In my problem, I have a function called void selectNegatives(int*&,int&,int*&,int&). What this function does is it iterates over an input array, removes negative ints from the input and place them in the output arr. For example an expected output is input -> -45 11 6 38 -12 0 output -> null //execute func input -> 11 6 38 0 output -> -45 -12 My current implementation is as follows. I have removed details of the function because I know the issue is not there. void selectNegatives( int*& inputArr, int& inputSize, int*& outputArr, int& outputSize ) { //details removed but I can add them if requested } My issue is passing int arr[] = {-45, 11, 6, 38, -12, 0}; from caller gives me cannot bind non-const lvalue reference of type 'int*&' to an rvalue of type 'int*' while passing int* arr = new int[]{-45, 11, 6, 38, -12, 0}; works. My current understanding is confusing me because isn't arr[] an lvalue?
Case 1 Here we consider the case when int arr[] = {-45, 11, 6, 38, -12, 0};. Here when passing arr as argument it decays(from int[6] to int*] due type decay but the problem is that this resulting expression is an rvalue(prvalue in particular) and since we can't bind an rvalue to a nonconst lvalue reference we get the mentioned error. This can also be seen from value category's documentation: A glvalue may be implicitly converted to a prvalue with lvalue-to-rvalue, array-to-pointer, or function-to-pointer implicit conversion. Case 2 Here we consider the case when int* arr = new int[]{-45, 11, 6, 38, -12, 0};. In this case, when passing arr as argument the expression arr is an lvalue which is allowed to be bound to a nonconst lvalue reference and so this time it works.
74,348,362
74,348,420
How to use smart pointers to store an
I have two classes. One class(Person) has a vector collection composed of pointers of the other class(Student). At run time, the Person class will call a method which will store a pointer to a Student class in the vector. I have been trying to do this with smart pointers to avoid Memory leak issues that can arise but I am struggling to do so. How would I go about it? My goal is for the Person class to have handles to objects that exist somewhere else in the code Class Student { public: string studentName Student(string name){ studentName = name; } } Class Person { public: vector <Student*> collection; getStudent() { cout << "input student name"; collection.push_back(new Student(name)); } }
You don't need to use smart pointers here. Place the objects directly into the vector and their lifetime is managed by the vector: std::vector<Student> collection; collection.emplace_back(name);
74,348,398
74,349,366
Makefile deferred compilation
I have a simple makefile with a variable for the compiler flags, it also contains some targets that modify that variable and append some flags. My point with it is to be able to run, for example: make debug perf that would in turn add to the variable the flags required to build under that configuration. The problem is that if I run it, it does compile the executable with the debug info, and then tries to compile with the performance tools, and obviously does nothing. Can make only execute the compilation step after both targets run? Makefile: CFLAGS = -std=c11 -Wall -pedantic -D_GNU_SOURCE executable: gcc $(CFLAGS) main.c -o exe debug: CFLAGS += -g debug: executable perf: CFLAGS += -D__PERF__ perf: executable Make version 4.2.1
One approach is to have different executable files for different flag combinations, ie executable # default to release build executable.dbg # with -g executable.perf # with -D__PERF__ executable.dbgperf # with both The two advantages are you're never unsure how some executable file was built, and you never accidentally test the wrong thing / waste time trying to debug something with no debug symbols, etc. Make's file dependency logic actually works correctly This does assume you have a manageable number of flag combinations. If there are too many, the profusion of targets may make your Makefile impractical.
74,348,765
74,349,126
Make alias to C types in C++ namespace
I have a DLL in pure C code. I would like to find a way to remove the library name prefix from the functions, classes, and structs; EX: // lib.h void foobar(); // lib.hpp namespace foo { bar(); } I would like to avoid simply writing a wrapper for every function, since I'd have to write it for every time I want to add a function. Is there a better / more efficient way of writing this? I started writing the wrapper idea, but there's a lot of functions to write this for. Void pointers worked a little better, but still had the same issue.
Unless you are worried about name conflicts between existing C++ function names and the C library, how about just using extern "C" (in your C++ code) and call it (from your C or C++ code). For example: extern "C" void f(int); // apply to a single function extern "C" { // or apply to a block of functions int g(double); double h(void); }; void code(int i, double d) { f(i); int ii = g(d); double dd = h(); // ... } When code is enclosed within an extern “C” block, the C++ compiler ensures that the function names are un-mangled – that the compiler emits a binary file with their names unchanged, as a C compiler would do. This approach is commonly used to accommodate inter language linkage between C++ and C. from this Reference more from cppprefference.com
74,348,968
74,349,113
Can I obtain different results from iterative and recurive functions?
My code is supposed to calculate the 100th element of the sequence $x_0=1 ; x_i=\dfrac{x_{i-1}+1}{x_{i-1}+2}, i=1,2, \ldots$ I wrote iterative and recursive functions, but the results are not equal. Is it due to the lost of decimals? Here is my driver code. The data from the file is i=100. int main() { int i; ifstream f ("data.txt"); f >> i; double x_0= 1.00; double x_100 = l(x_0, i); ofstream g ("results.txt", ios::app); g <<"\n100th element (by looping): " << x_100; x_100 = r(x_0); g <<"\n100th element (by recursion): " << x_100; return 0; } l() is iterative function, r() is recursive function double l(double x, int i) { for (int j = 0; j<i ; j++){ x = (x + 1)/(x+2); } return x; } double r(double x) { if (x == 0) return 1; else return (r(x-1) + 1) / (r(x-1) + 2); } Here are the results 100th element (by looping): 0.618034 100th element (by recursion): 0.666667
I the recursive function you do (r(x-1) + 1) / (r(x-1) + 2) With x == 1.0 that's equal to (r(1-1) + 1) / (r(1-1) + 2) That's of course equal to (r(0) + 1) / (r(0) + 2) And since r(0) will return 1 that equation is (1.0 + 1) / (1.0 + 2) There's no further recursion. The result is 2.0 / 3.0 which is 0.66667. The iterative function l on the other hand will do 100 iterations where each iteration will change the value of x, making it even smaller and smaller. The functions simply does different things, leading to different results.
74,349,144
74,349,200
How to re-throw an abstract class error from a catch block
I need to perform some action inside a catch block then throw the same exception I got: #include <string> #include <iostream> class AbstractError { public: virtual std::string toString() const = 0; }; class SomeConcreteError : public AbstractError { public: std::string toString() const { return "division bt 0"; } }; class SomeOtherError : public AbstractError { public: std::string toString() const { return "null pointer deref"; } }; void foo(int i) { if (i > 2) { throw SomeConcreteError(); } else { throw SomeOtherError(); } } int main(int argc, char **argv) { try { foo(argc); } catch (const AbstractError &e) { std::cout << e.toString() << "\n"; // do some action then re-throw throw e; // doesn't work ... } return 0; } Here is the error I get: main.cpp:28:15: error: expression of abstract class type ‘AbstractError’ cannot be used in throw-expression 28 | throw e; | ^
This would throw a copy of e: throw e; but it's abstract so that can't be done. You need to rethrow the same exception: throw;
74,349,658
74,351,903
Parse a String in C++ and connect input-arguments to existing variables
I want to read an input string and connect their values to variables in my class. Some example Inputs might be: 78 C 15.48 3 B 87 P 15 0 .. The first argument is an int from 0-100, second a char and third int or float. A String can consist of one, two or three arguments which are separated by space. After reading a line, this program does some calculations and then expects another input until a 0 is entered or a break occurred. To read an input String, i'm currently using std::string str; std::getline(std::cin, str); My program already has the variables int firstArgument; char secondArgument; float thirdFloatArgument; int thirdIntArgument; now, lets say str is: 46 C 87.3 after reading the line my variables should be: firstArgument = 46; secondArgument = 'C'; thirdFloatArgument = 87.3; How can I extract the Information from the input String? I was thinking about counting the spaces to see how much values are given and then separating the string via this delimiter,as the amount of arguments might vary. So: int count = 0; int length = str.length(); for(int i = 0; i < length; i++){ int c = str[i]; if(isspace(c)){ count++; } } with space count being 2 I now know that 3 arguments were passed, but I don't know how to go on from there. Using std:istringstream might be an option but from what I've seen online it is mostly used in a while loop to print each word of a string in a new line or like that. But my input can vary in the amount of arguments so a loop would not work. I think I need something like: "String before first ' ' is firstArgument, String between first and second ' ' is secondArgument, string after second ' ' is either thirdFloatArgument or thirdIntArgument (respectively if only one or two arguments are given, which can be determined with the amount of spaces). But how would I do this? Or are there some easier approaches? Big thanks in advance!
As Some programmer dude mentioned it is a good idea to use std::istringstream to convert values from string to other data types. It allows you to treat input string the same way as you treat std::cin. Here is a code snippet that you can use in your case: #include <string> #include <iostream> #include <algorithm> #include <sstream> struct Arguments { int first{}; char second{}; double third{}; }; Arguments parseArgs(const std::string& inputLine) { Arguments args; const int argc = std::ranges::count(inputLine, ' '); std::istringstream stream(inputLine); if (argc >= 0) { stream >> args.first; } if (argc >= 1) { stream >> args.second; } if (argc >= 2) { stream >> args.third; } return args; } int main() { std::string inputLine{}; std::getline(std::cin, inputLine); const auto args = parseArgs(inputLine); std::cout << args.first << ", " << args.second << ", " << args.third << "\n"; } Note that you have to compile this example using C++20 because I used std::ranges. If you do not have compiler that supports this standard you can use std::count(inputLine.cbegin(), inputLine.cend(), ' ');
74,349,900
74,353,445
What is the role of struct data member aeron_udp_channel_transport_stct::bindings_clientd in Aeron C++ code?
The aeron_udp_channel_transport_stct::bindings_clientd is only found be used in aeron_udp_channel_transport_init function which set the bindings_clientd to NULL without further operations. Except some modification and assert in test cases. In the test case, it is assigned as struct aeron_test_udp_bindings_state_stct, which containes some state counter. What role does this data member play in Aeron? What is the proper usage of bindings_clientd?
TL;DR unless you are writing a custom network binding don't concern yourself with this field. The Aeron C driver has support for adding different network bindings implementations (see aeron_udp_channel_transport_bindings_stct). In the OSS repo there is only support for traditional OS (Linux, Mac, Windows) networking. However, if a user wanted to add an additional implementation that used a different network API and needed to carry some implementation specific information on each transport instance, this would be the field to add it to. In theory for the UDP implementation, it could be refactored towards having a structure that held the file descriptors here. The test driver carries some state information in that field so that behaviour can be asserted within the tests. There also exists commercial extensions to the C driver (e.g. for DPDK) that make use of this field too.
74,350,258
74,350,913
using uninitialized memory warning and else in cpp
there is warnings in c++ i can't solve it i have Visual Studio 2019 first i got error with #include "pch.h" and 3 warnings -using uninitialized memory : in processesSnapshot ` while (Process32Next(processesSnapshot, &processInfo)) ` -argument conversion from 'unsigned __int64' to 'unsigned long', possible loss of data -argument conversion from 'unsigned __int64' to 'DWORD', possible loss of data ` MODULEENTRY32 module = GetModule("ac_client.exe", pid); HANDLE phandle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid); ` ` #include "pch.h" #include <iostream> #include <Windows.h> #include <TlHelp32.h> DWORD GetPID(const char* ProcessName) { PROCESSENTRY32 processInfo; processInfo.dwSize = sizeof(processInfo); HANDLE processesSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL); if (processesSnapshot == INVALID_HANDLE_VALUE) return 0; Process32First(processesSnapshot, &processInfo); if (!strcmp(processInfo.szExeFile, ProcessName)) { CloseHandle(processesSnapshot); } while (Process32Next(processesSnapshot, &processInfo)) { if (!strcmp(processInfo.szExeFile, ProcessName)) { CloseHandle(processesSnapshot); } } CloseHandle(processesSnapshot); return processInfo.th32ProcessID; } MODULEENTRY32 GetModule(const char* moduleName, unsigned long ProcessID) { MODULEENTRY32 modEntry = { 0 }; HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE | TH32CS_SNAPMODULE32, ProcessID); if (hSnapshot != INVALID_HANDLE_VALUE) { MODULEENTRY32 curr = { 0 }; curr.dwSize = sizeof(MODULEENTRY32); if (Module32First(hSnapshot, &curr)) { do { if (!strcmp(curr.szModule, moduleName)) { modEntry = curr; break; } } while (Module32Next(hSnapshot, &curr)); } CloseHandle(hSnapshot); } return modEntry; } int main() { std::cout << "Hello World!\n"; unsigned long long pid = GetPID("ac_client.exe"); MODULEENTRY32 module = GetModule("ac_client.exe", pid); HANDLE phandle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid); unsigned long long result; int ammodesiredvalue = 999999; ReadProcessMemory(phandle, (void*)((unsigned long long)module.modBaseAddr + 0x0010B1E0), &result, sizeof(result), 0); ReadProcessMemory(phandle, (void*)((unsigned long long)result + 0x54), &result, sizeof(result), 0); ReadProcessMemory(phandle, (void*)((unsigned long long)result + 0x14), &result, sizeof(result), 0); //ReadProcessMemory(phandle, (void*)((unsigned long long)result + 0x14), &result, sizeof(result), 0); WriteProcessMemory(phandle, (void*)((unsigned long long)result + 0x14), &ammodesiredvalue, sizeof(ammodesiredvalue), 0); std::cout << "Your ammo value is " << result << std::endl; system("pause"); } ` i looking for fix this error and warnings
Your code has a number of problems. I'm going to look at one small section, and point out what look to me like obvious problems. Not sure if they're the source of the symptoms you're seeing, but ... Process32First(processesSnapshot, &processInfo); if (!strcmp(processInfo.szExeFile, ProcessName)) { CloseHandle(processesSnapshot); } So here if we found the right process, we close the process snapshot, but then: while (Process32Next(processesSnapshot, &processInfo)) { ...we try to continue using the process snapshot, even if it's already been closed. Then: if (!strcmp(processInfo.szExeFile, ProcessName)) { CloseHandle(processesSnapshot); } ...we check whether we have the right process, and (again) close the snapshot if we found it. But we don't break out of the loop--so again, we try to continue using the snapshot, even if we've closed it. Then: } CloseHandle(processesSnapshot); ...when we exit the loop, we close the snapshot yet again. At this point, we've potentially closed our snapshot three times, and continued using it after it was closed in a couple of different places. My personal inclination is that any time I see something that needs to be opened and later closed (or something along those lines) I think of using RAII/SBRM to deal with it. That means I'd create a class to manage the process snapshot. I'd create the snapshot in the class' constructor, and close it in the class' destructor, and add other member functions to obtain the contents of the current item, advance to the next item, and so on. Given that this iterates things, it also makes sense (in my opinion) to have this class act as an actual iterator. // warning: untested code. class ProcessIterator { HANDLE snapshot; bool valid; PROCESSENTRY32 processInfo; public: using iterator_category = std::input_iterator_tag; using difference_type = std::ptrdiff_t; // not really, but it'll probably do for now. using value_type = PROCESSENTRY32; using pointer = PROCESSENTRY32 *; using reference = PROCESSENTRY32 &; ProcessIterator(DWORD ID) : snapshot(CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, ID)) { if (!snapshot) throw std::runtime_error("Unable to open process snapshot"); valid = Process32First(snapshot, &processInfo); } ProcessIterator() : valid(false) {} ProcessIterator operator++() { valid = Process32Next(snapshot, &processInfo); return *this; } PROCESSENTRY32 operator*() const { return processInfo; } bool operator==(ProcessIterator other) { // only invalid iterators are equal: return (!valid) && (!other.valid); } ~ProcessIterator() { CloseHandle(snapshot); } }; Since this is a normal iterator, we can use it for normal iterator "stuff", such as finding an entry using std::find_if: DWORD getPid(char const *filename) { auto p = std::find_if(ProcessIterator(0), ProcessIterator(), [&](PROCESSENTRY32 const &p) { return !std::strcmp(filename, p.szExeFile); }); return p->th32ProcessID; }
74,350,795
74,353,209
How to store and process possibly duplicate distributed class coupling information in C++?
I'm writing a template<class ...Ts> class SortedTypeHolder. During compile time instantiation SortedTypeHolder must collect distributed information about all provided ...Ts from their headers for future sorting. The gathered information describes which classes depend on others in a form of template<typename A, typename B> class Pair specializations. I want to provide multiple dependees for one depender class at once with a macro DEFINE_PAIRS. #include <boost/preprocessor.hpp> template<class ...Ts> class SortedTypeHolder; template<typename Depender, typename Dependee> class Pair : std::false_type {}; //doesn't depend, the default #define TRUESPEC( _, Depender, Dependee ) \ template<> class Pair<Depender, Dependee> : public std::true_type {}; //depends #define DEFINE_PAIRS( Depender, ... ) \ BOOST_PP_LIST_FOR_EACH( TRUESPEC, Depender, BOOST_PP_TUPLE_TO_LIST( ( __VA_ARGS__ ) ) ) class A {}; class B {}; class C {}; class D {}; // from A.hpp DEFINE_PAIRS( A, B, C, D ) // from B.hpp DEFINE_PAIRS( B, A, C, D ) // from D.hpp. this dependency is reverse yet allowed //DEFINE_PAIRS( A, D ) //Error C2766 explicit specialization; 'Pair<A,D>' has already been defined ... SortedTypeHolder<A,B,C,D> holder; I also want my code to allow duplicate dependencies without generating new specializations, but my current realization produces an error in such case. Please give me an advice how do I enhance the code to allow duplicate dependencies. If it is possible to define multiple Pairs at once without macros, it will be great.
Just use function declarations. You don't need to define them, can easily extract the parameter types, can have duplicate forward declarations with no problem, and get ADL for free. void dependency(A, B, C, D); // A depends on B, C, D or, if it's easier to use std::tuple<B, C, D> dependency(A); You'll need to either use SFINAE to handle classes with no dependencies, or have a special guaranteed-worst-match NoDepTagType dependency(...);
74,351,076
74,351,185
How to initialize array elements with their indices
I would like to find an elegant way of initializing C++ array elements with their indices. I have a lot of code that looks like this: static constexpr size_t ELEMENT_COUNT = 8; MyObject x[ELEMENT_COUNT] = {{0}, {1}, {2}, {3}, {4}, {5}, {6}, {7}}; Where MyObject is effectively, struct MyObject { size_t mMyIndex; MyObject(size_t myIndex) : mMyIndex(myIndex) {} }; The problems should be already clear: when ELEMENT_COUNT changes, I have to adapt the initializer list, which feels very un-C++. And if ELEMENT_COUNT is, say, 1000, this becomes impractical. Is something like the following possible in C++?: MyObject mObjects[ELEMENT_COUNT] = initialize_array_with_indices<ELEMENT_COUNT>(); Does such a function like initialize_array_with_indices<N>() exist in the std library? Is it possible? Using std::array<> is an option, if that gets me further.
It is impossible to intialize a built-in array like this. Arrays can only be default-initialized, value-initialized or aggregate-initialized (with exception for string literals). The only one of these allowing to specify different values for the elements is aggregate initialization and that requires explicitly listing each element. (There is one other exception specific to non-static array members of classes. They may be initialized by copy through implicitly defined constructors of the enclosing class. However that still doesn't allow writing an initializer like you want.) So you have to use std::iota or a loop after the initialization. If you use std::array instead of a built-in array, you can define it as template<typename T, std::size_t N> constexpr auto initialize_array_with_indices() { return []<std::size_t... Is>(std::index_sequence<Is...>){ return std::array<T, N>{Is...}; }(std::make_index_sequence<N>()); } To be used like auto mObjects = initialize_array_with_indices<MyObject, ELEMENT_COUNT>(); The implementation above requires C++20. It can be written (slightly longer) for previous versions as well. Specifically before C++20 lambdas can't have explicit template parameters, so a helper function must be used instead (or a constexpr array of indices can be filled first with the approach below and then std::apply used on it to get the indices as a pack into the lambda). Also before C++17 it will require copy/move-constructibility of T. An implementation that assumes that default-initialization of MyObject is possible and not undesirable would be much more straight-forward. (It would simply default-initialize a std::array and then loop through it to set the indices or use std::iota on it.)
74,351,419
74,351,621
Should using the "new" keyword in the factories be avoided?
As I went through our codebase, I saw using the new keyword for memory allocation in almost every factory. It makes perfect sense, and is OK until the users are disciplined and assigning created instances to the smart pointers (that are forced by our CS, or at last do proper memory management). But digging deeper, I found out it is not that case every time, and we are assigning the returned instances to the raw pointers on multiple occasions without properly freeing them anywhere, and I feel like using the factories makes this even easier as it hides to some extent the allocation part. Is there any possibility or tweak, how to use the factory, but assure that it is implemented as memory safe as possible? When I was thinking about it, it looks simple - just return a unique/shared pointer and the problem is solved, but this is already assuming that we know the exact usage of the instance from the ownership perspective. So, to my question - should the memory allocation using the new be avoided even in factories? Is there a way how to solve this in an elegant way, and without relying on the caller of the create method to behave in a memory responsible way?
The textbook solution is, of course, as πάντα ῥεῖ wrote: use a T::create() member function that returns either std::unique_ptr<T> or std::shared_ptr<T>, plus make ctors private; and that should work in most cases. However, as you wrote, there are cases where you need an instance 'on the spot'. In such cases, the overhead of smart pointers (and heap allocation) is simply too much to pay, and in C++ we don't tend to pay for what we don't use. In such cases, you might ensure that an instance is created on the stack by accepting a 'visiting' lambda on the newly constructed instance: class T { private: T() {} // other ctors, etc. public: template<typename... Args> std::shared_ptr<T> create(Args&&... args) { return std::make_shared(std::forward<Args>(args)...); } template<typename V, typename... Args> static void with_created(V v, Args&&... args) { T t; v(t); // v accepts T& or const T& } }; Usage of the latter: int main() { T::with_created([&](T& t) { /* here you can manipulate t */ }, /* ctor args of T */); }
74,351,800
74,355,835
Analyze the run time of the function below and assume worst case scenario (in terms of n)
i think that the loops runs o(N) times and wanted to confirmed that and even to expanding knowledge over the steps. Can anyone explain this?
Let k be the least positive number such that 2^k > n. Observe that your first iteration runs no more than 2^k times. since, n < 2^k, n/2 < 2^{k-1}, hence your second loop runs no more than 2^{k-1} times, third loop runs 2^{k-2} time, so on and so forth. Total number of iterations can be upper bounded by 2^k + 2^{k-1} .... 2^0 = 2^{k+1}-1. We assumed that k is the least postive number such that 2^k > n, which implies 2^{k-1} <= n multiplying by 4 on both sides and substracting gives us, 2^{k+1}-1 <= 4n-1 hence total number of iterations is O(n). Although the upper bound 4n-1 is sloppy, it is enough to prove asymtotics. (in reality your loop runs approximately 2n times)
74,352,530
74,352,956
Iterating over Variadic arguments
I'm sure this question has been asked before, but I can't seem to find something as simple as what I'm trying to do. Essentially, I just want to make sure the code triggers each parameter, calling any functions that may be sent as inputs. My biggest worry here is that optimizations may remove some of the calls, changing the result. I was using the following syntax. It seemed to trigger the function calls the way I want, but it has the strange result of triggering the arguments in reverse order - the last argument is called first, and the first argument is called last: template <typename... PARMS> uint PARMS_COUNT(PARMS&& ... parms) { return static_cast<uint>( sizeof...(parms) ); } This was my first guess as to how to do the same thing (edit: this does not change the order - it still happens in reverse, because the order is being determined by the function parameter evaluation, rather than what order the function uses them in): template <typename FIRST> constexpr uint PARMS_EXPAND(FIRST &&first) { return static_cast<uint>( sizeof(first) > 0 ? 1 : 0 ); } template <typename FIRST,typename... PARMS> constexpr uint PARMS_EXPAND(FIRST &&first,PARMS&& ... parms) { return static_cast<uint>( sizeof(first) > 0 ? 1 : 0 ) + PARMS_EXPAND( std::forward<PARMS>(parms)... ); } I tested this in a few places, but then realized that regardless of how much testing I do, I'll never know if this is a safe way to do it. Is there a standard or well known method to pull this logic off? Or even better, some built in system to iterate over the arguments and "access them" in the correct order? To better explain why I would want to trigger code like this, consider a function that can add new objects to a parent: void AddObject(/*SINGLE UNKNOWN INPUT*/) { ... } template <typename... PARMS> AddObjects(PARMS&& ... parms) { PARAMS_EXPAND( AddObject(parms)... ); }
When you write void AddObject(T); template <typename... PARMS> AddObjects(PARMS&& ... parms) { PARAMS_EXPAND( AddObject(parms)... ); } you're making a single top-level function call to PARAMS_EXPAND with sizeof...(PARMS) arguments. What happens inside PARAMS_EXPAND is essentially irrelevant because, like every other function call, the arguments are evaluated before the function is entered. And, like every other function call, the argument expressions are intederminately sequenced with respect to each other. So, your goal of evaluating AddObject(parms) for each parameter in order has failed before control reaches inside PARAMS_EXPAND at all. Fortunately, C++17 gave us a way of evaluating operations on parameter packs in order without relying on function call semantics: the fold expression: (AddObject(parms), ...); Although this looks a bit like a function call, it's actually a right fold over the comma operator, expanded like (AddObject(p0) , (... , (AddObject(pN-1) , AddObject(PN)))); which does indeed evaluate its arguments in left-to-right order, exactly as you want.
74,352,686
74,357,587
Conan import error in gitlab pipeline - Cannot load recipe
Here is the error getting during build-job in gitlab pipeline. This was initially working for days in the pipeline build and without any update in the code repository, import error started to happen. It would be nice if anyone can shed some light on it. Conan version in the pipeline runner image is Conan version 1.51.3 gtest/1.10.0: Not found in local cache, looking in remotes... gtest/1.10.0: Trying with 'conancenter'... Downloading conanmanifest.txt Downloading conanfile.py Downloading conan_export.tgz gtest/1.10.0: Downloaded recipe revision 0 ERROR: gtest/1.10.0: Cannot load recipe. Error loading conanfile at '/root/.conan/data/gtest/1.10.0/_/_/export/conanfile.py': Unable to load conanfile in /root/.conan/data/gtest/1.10.0/_/_/export/conanfile.py File "/usr/lib/python3.10/imp.py", line 172, in load_source module = _load(spec) File "<frozen importlib._bootstrap>", line 719, in _load File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "/root/.conan/data/gtest/1.10.0/_/_/export/conanfile.py", line 6, in <module> from conan.tools.files import apply_conandata_patches, export_conandata_patches, copy, get, replace_in_file, rm, rmdir ImportError: cannot import name 'export_conandata_patches' from 'conan.tools.files' (/usr/local/lib/python3.10/dist-packages/conan/tools/files/__init__.py) Looking forward to hearing from you soon. Best, Honey Honey Sukesan
The export_conandata_patches is available since Conan 1.52.0. You need to update your Conan client version: pip install -U conan Since Conan 1.52.0, required_conan_version is validated before parsing those imported modules, so it fail soon and validate your Conan client version first.
74,352,886
74,353,117
PInvoke C++ dll from C# throws Exception
The project I am working on has a case where I have to read and display hardware info, for which they have a function written in a C++ DLL, and I am writing a C# stub to PInvoke it. I am fairly new to PInvoke, and hold beginner status in C# and C++ in general, as I mostly work in the Java space. The issue here is that I am getting an exception, I feel like there is some marshaling issue going on here, which is causing this exception, but please correct me if I am wrong. Can you please help me spot the issue? Also, I did try combining multiple MarshalAs options and different data types. In addition to the complication as it is, the function takes in a reference to a struct as an argument, and the struct itself has a nested struct within. Also, it returns a long as a flag I believe, when called with no arguments returns 0 with no exception, which is interesting. =========================================================================================================== Part of sample hardware operation C++ dll header. =========================================================================================================== #define APOINTER * typedef unsigned char BYTETYPE; typedef BYTETYPE CHARTYPE; typedef unsigned long int ULONGTYPE; typedef HDINFO APOINTER PTR_HDINFO; typedef struct VERSION { BYTETYPE major; BYTETYPE minor; }VERSION; typedef VERSION APOINTER PTR_VERSION; typedef struct HDINFO { VERSION hardwareVersion; CHARTYPE hardwareManufactureID[32]; /* blank padded */ ULONGTYPE hardwareflags; /* must be zero */ CHARTYPE hardwareDesc[32]; /* blank padded */ VERSION apiVersion; }HDINFO; typedef HDINFO APOINTER PTR_HDINFO; extern "C" __declspec(dllexport) ULONGTYPE GetHardwareInfo(PTR_HDINFO pSoInfo); =========================================================================================================== Sample C# code for PInvoke. Throws Exception =========================================================================================================== using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Runtime.InteropServices; namespace ConsoleHardwareApp { [StructLayout(LayoutKind.Sequential, Size =1)] struct VERSION { byte majorVersion; byte minorVerison; } [StructLayout(LayoutKind.Sequential, Size =1)] struct HDINFO { VERSION hardwareVersion; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] string hardwareManufactureID; int hardwareflags; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] string hardwareDesc; VERSION apiVersion; } class Program { [DllImport("sampleHardwareOp.dll")] public static extern int GetHardwareInfo(ref IntPtr hdInfoPtr); static void Main(string[] args) { HDINFO hdInfo = new HDINFO(); IntPtr hdInfoPtr = new IntPtr(); hdInfoPtr = Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof(HDINFO))); Marshal.StructureToPtr<HDINFO>(hdInfo, hdInfoPtr, false); int rv = 1; rv = GetHardwareInfo(ref hdInfoPtr); //Exception thrown here Console.WriteLine(rv); Console.ReadKey(); } } } The exception: ConsoleHardwareApp.Program::GetHardwareInfo' has unbalanced the stack. This is likely because the managed PInvoke signature does not match the unmanaged target signature. Check that the calling convention and parameters of the PInvoke signature match the target unmanaged signature.
Without concise details about which C++ compiler was used to make the DLL, what size its long data type is (may be 32bit or 64bit), what alignment settings are used, if any structure padding is present, etc, then a translation to C# is difficult. However, your C# code should probably look something more like the following instead: namespace ConsoleHardwareApp { [StructLayout(LayoutKind.Sequential/*, Pack=4 or 8*/)] struct VERSION { byte major; byte minor; } [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi/*, Pack=4 or 8*/)] struct HDINFO { VERSION hardwareVersion; [MarshalAs(UnmanagedType.ByValTStr, SizeConst=32)] string hardwareManufactureID; uint hardwareflags; // or ulong, depending on the C++ compiler used [MarshalAs(UnmanagedType.ByValTStr, SizeConst=32)] string hardwareDesc; VERSION apiVersion; } class Program { [DllImport("sampleHardwareOp.dll", CallingConvention=CallingConvention.Cdecl)] public static extern uint/*or: ulong*/ GetHardwareInfo(ref HDINFO pSoInfo); static void Main(string[] args) { HDINFO hdInfo = new HDINFO(); uint rv = GetHardwareInfo(ref hdInfo); Console.WriteLine(rv); Console.ReadKey(); } } } The CallingConvention in particular is very important. The default calling convention in C++ is usually __cdecl (but can be changed in compiler settings), however in C# the default CallingConvention in DllImport is CallingConvention.Winapi, which is __stdcall on Windows. A calling convention mismatch can easily corrupt the call stack, causing the error you are seeing.
74,353,155
74,353,258
Side effect of volatile read/write of nullptr
I was watching this c++ lection (it's in russian). At around 16:10 the lector asked an open question: Having this code: int* foo() { volatile auto a = nullptr; int* b = a; return b; } int main() {} Clang generates the following assembly for foo (-Ofast) mov qword ptr [rsp - 8], 0 # volatile auto a = nullptr; xor eax, eax ret Meaning the compiler assumes there is no side effect for reading from a and basically removes int* b = a; part of the code. GCC on the other hand generates a bit different code mov QWORD PTR [rsp-8], 0 # volatile auto a = nullptr; mov rax, QWORD PTR [rsp-8] # int* b = a; xor eax, eax ret Here compiler believes reading from a does produce the side effect and leaves everything as is. The question is what is the correct behaviour according to C++20 standard?
The type of a will be volatile std::nullptr_t. std::nullptr_t isn't really required to have any internal state, although it is specified to have the same size as void*. Only the conversion behavior is specified for this type. There is no need for std::nullptr_t to store a value in the memory it occupies. All conversion behavior only depends on the fact that the source has std::nullptr_t type. So there doesn't need to be a 0 value written or read there. The assignment int* b = a; does not depend on any state or value stored in a, only on its type. I would say both behaviors are correct. What exactly the meaning of the observable side effect of volatile access is is anyway implementation-defined and if std::nullptr_t is implemented to not actually use any of its memory to store value, then one wouldn't expect any instruction loading/storing from/to it to be generated for the initialization and the implicit conversion in int* b = a; anyway. But if std::nullptr_t is implemented similar to a pointer which always has value 0, then it would be reasonable to expect a store and load. Note: The answer originally claimed that std::nullptr_t could be implemented in any number of bytes of storage, which is wrong, as the standard requires sizeof(std::nullptr_t) == sizeof(void*). See [basic.fundamental]/14. In fact after having a look at the standard, I think GCC's behavior is more dubious. At least according to a note the lvalue-to-rvalue conversion on a is not supposed to access the nullptr_t glvalue. This would mean that there may not be any load from a's memory location because it would introduce the possibility of a data race that shouldn't be presented by that rule.
74,353,565
74,353,684
Copy char to a array with a function - C++
Function.h void copyArray(char, char); Main.cpp void copyArray(char word[], char temp[]) { for (int i = 0; i < 50; i++) temp[i] = word[i]; } auther.cpp copyArray("CHAMPAGNE", char myArray[50]); Output C2664 'void copyArray(char,char)': cannot convert argument 1 from 'const char [10]' to 'char' already googled the error, look for function precoded, found nothing I must not use string
First: The declaration and definition don't match since the declaration specifies that the function takes two chars while the definition specifies that the function takes two char*: void copyArray(char, char); // declaration void copyArray(char word[], char temp[]) { // definition for (int i = 0; i < 50; i++) temp[i] = word[i]; } You need to make the declaration the same as the definition: void copyArray(char[], char[]); // or void copyArray(char*, char*); ... but, in order to copy from string literals, you need to make the first argument take a const char* since string literals consists of const chars. void copyArray(const char word[], char temp[]); There are however not 50 chars in "CHAMPAGNE" so trying to copy that many will make your function access "CHAMPAGNE" out of bounds (with undefined behavior as a result). You shouldn't copy beyond the \0 terminator: void copyArray(const char* word, char* temp) { do { *temp++ = *word; } while(*word++ != '\0'); // stop when \0 has been copied } But make sure that temp has enough room for the larget string you try to copy into it. If you want to copy CHAMPAGNE into myArray, you need to declare myArray first and supply it as an argument to the function: char myArray[50]; copyArray("CHAMPAGNE", myArray); Demo
74,353,628
74,353,675
Initialize const struct members from a static member function when class is initialized
I am experimenting with the const and static keywords and am getting stuck with my class design. The class FileReader contains a struct Params with its own default constructor and a static method to initialize the member variables of the struct. The parameters in Params struct need to be initialized only once when the class is initialized. Therefore, it is marked as const. I understand that, normally, that the members of the struct can be modified from a non-static function if they are declared mutable. My question is: Is it possible to modify the const struct members from a static member function? If so, how? If not, what would be the best/better way of initializing a const struct when the parameters can only be initialized during runtime or when a file is read? The class is defined in the header as follows: class FileReader { public: FileReader(const std::string& iniFilePath); private: struct Params { private: Params() = default; public: static Params createFromIniFile(const std::string iniFilePath); // some member variables }; const Params params; // will be initialized when class is initialized! }; The static method is defined in cpp as follows: auto FileReader::Params::createFromIniFile(const std::string iniFilePath) -> Params { Params result; // parse ini file readFile(iniFilePath); // initialize params ... return result; } FileReader::FileReader(const std::string& iniFilePath) { //call static initializer params = Params::createFromIniFile(iniFilePath); // error: params cannot be initialized this way } I have tried the approach mentioned here using a fake pointer and it worked, but I want to avoid using this and raw pointers.
You are doing the initialization in the wrong place. Once you've enter the body of the constructor all class members have already been initialized. What you need to do is initializer params in the class member initialization list like FileReader::FileReader(const std::string& iniFilePath) : params(Params::createFromIniFile(iniFilePath)) { // constructor body }
74,354,585
74,397,484
How to avoid deprecated-copy warnings?
Here is some simplified code. It's not mine, but I'm adapting it for a project of mine. It's part of a sizeable codebase I'm importing, and which I don't want to change more than absolutely necessary. void function (object& out_thing) { object thing; #pragma omp nowait for (int k = 0 ; k < 5 ; k++) { object* things[2]; float scores[2]; for (i = 0; i < 2 ; i++) scores[i] = evaluateThings(things[i], parameter1, parameter2); if (scores[1] < scores[0]) { scores[0] = scores[1]; things[0] = things[1]; } thing = *(things[0]); } out_thing = thing; } When compiled, I get warnings that the implicitly declared thing = *(things[0]) and out_thing = thing are deprecated [-Wdeprecated-copy] because I have a user-provided copy constructor. I guess the compiler wants me to write object thing(*(things[1]) but I can't because I need to declare object thing before the omp pragma, and I can't write object out_thing(thing) at the end because out_thing is already defined as one of the arguments passed to the function. Is there any way to recode this to get rid of the warnings? (I can actually get rid of the first one by changing object thing; to object* thing = NULL and then later on changing thing = *(things[0]); to thing = things[0]; but that requires me to change out_thing = thing; to out_thing = *thing; and I still get the warning for that deprecated copy; I'd like to get rid of both, ideally, if it's possible without extensive changes elsewhere in the code base and without being harmful to performance etc.)
The warning -Wdeprecated-copy warns about a missing/deleted user-declared copy assignment operator, when there is the user-declared destructor ~object. If there is a user-declared destructor, missing a copy constructor or a copy assignment operator is likely the error in the code. You should add a custom copy assignment operator object& operator=(const object&); See What is The Rule of Three?.
74,354,601
74,372,027
Handing custom HINSTANCE to MFC Dialog
I am porting the GUI of a very old plugin from win32 to MFC. The dialog used to be started by invoking something like: DialogBoxParam( GetDLLInstance(), ..., GetHWND(), ..., ... ) When trying to debug why my MFC solution doesn't work, I found, that above code would fail if I replace GetDLLInstance() by nullptr. So, for the code to work, it seems to be imperative, to provide it with the correct HINSTANCE, as the default one seems to be wrong. As MFC is just a wrapper for those win32 functions, I assume it also has to be provided with this information. However, when starting a CDialogEx-derived class, I didn't find a way to set a HINSTANCE. So how do I tell the MFC widgets the correct HINSTANCE for their internal call to DialogBoxParam( ... )?
AfxSetResourceHandle sets the HINSTANCE handle that determines where the default resources of the application are loaded. As @RbMm said, you need to set before rundialog and restore instantly. For Modeless Dialog Box, HMODULE hPrevious = AfxGetResourceHandle(); AfxSetResourceHandle(hMod); CMyDialog *pDlg = new CMyDialog(); pDlg->Create(ID_DLG, this); AfxSetResourceHandle(hPrevious); pDlg->ShowWindows(SW_SHOW); For Modal Dialog Box, see the answer.
74,354,869
74,359,969
Is asio::serial_port able to check physical disconnection?
I'm working with boost::asio library for serial communications, and got some problems using it. Below is my code with the problem. std::unique_ptr<asio::serial_port> port_; asio::io_service io_; // Connect serial port 'COM8' port_ = std::make_unique<asio::serial_port>(asio::serial_port(io_, "COM8")); std::cout << port_->is_open() << std::endl; // True Sleep(5000); /// **Now I unplug the device connected to the COM8 port of my PC.** std::cout << port_->is_open() << std::endl; /// Still printed true. /// I think the reason @asio::serial_port::is_open() returns true /// is because I didn't called @asio::serial_port::close() before. /// Then how can I check the physical disconnection? After I unplugged the device, how can I know whether the device is still available in programmatically?
You can detect it when attempting a read/write operation: E.g. from the exception overload of write_some: boost::system::system_error Thrown on failure. An error code of boost::asio::error::eof indicates that the connection was closed by the peer.
74,355,562
74,355,579
Why Obj.*A is out of scope?
Here is part of my class assign_obj, constructor and operator that I want to print the object. When trying to compile operator I am getting error : error: 'A' was not declared in this scope for(assign_obj::item anItem : obj.*A){ Why is that? If I try obj.A instead, I get error for the forloop as C++ can not loop a pointer of dynamic array. class assign_obj{ private: struct item{ char value; int count; }; item * A; //pointer A pointing to something of type Item int size; public: assign_obj(); assign_obj(std::string); friend std::ostream& operator<<(std::ostream & out, assign_obj & obj); //Constructor assign_obj::assign_obj(string aString){ size = aString.size(); A = new item[size]; item myItem; for(int i = 0; i < size; i++){ myItem = {(char)toupper(aString[i]), 1}; A[i] = myItem; } } // Print operator std::ostream& operator<<(std::ostream & out, assign_obj & obj){ out <<"[ "; for(assign_obj::item anItem : obj.*A){ out << anItem.value; out << ":"; out << anItem.count; out << " "; } out <<"]"; return out; }
You can't use a for loop that way for a dynamically allocated array. You can use a plain old for loop for your plain old array. std::ostream& operator<<(std::ostream & out, assign_obj & obj){ out <<"[ "; for (size_t i = 0; i < obj.size; i++) { out << obj.A[i].value << ":" << obj.A[i].count << " "; } out <<"]"; return out; }
74,355,714
74,355,874
Correctness of multiplication with overflow detection
The following C++ template detects overflows from multiplying two unsigned integers. template<typename UInt> UInt safe_multiply(UInt a, UInt b) { UInt x = a * b; // x := ab mod n, for n := 2^#bits > 0 if (a != 0 && x / a != b) cerr << "Overflow for " << a << " * " << b << "." << endl; return x; } Can you give a proof that this algorithm detects every potential overflow, regardless of how many bits UInt uses? The case cannot result in overflows, so we can consider . It seems that the correctness proof boils down to leading to a contradiction, since x / a actually means . When assuming , this leads to the straightforward consequence thus which contradicts n > 0. So it remains to show or there must be another way. If the last equation is true, WolframAlpha fails to confirm that (also with exponents). However, it asserts that the original assumptions have no integer solutions, so the algorithms seems to be correct indeed. But it doesn't provide an explanation. So why is it correct? I am looking for the smallest possible explanation that is still mathematically profound, ideally that it fits in a single-line comment. Maybe I am missing something trivial, or the problem is not as easy as it looks. On a side note, I used Codecogs Equation Editor for the LaTeX markup images, which apparently looks bad in dark mode, so consider switching to light mode or, if you know, please tell me how to use different images depending on the client settings. It is just \bg{white} vs. \bg{black} as part of the image URLs.
To be clear, I'll use the multiplication and division symbols (*, /) mathematically. Also, for convenience let's name the set N = {0, 1, ..., n - 1}. Let's clear up what unsigned multiplication is: Unsigned multiplication for some magnitude, n, is a modular n operation on unsigned-n inputs (inputs that are in N) that results in an unsigned-n output (ie. also in N). In other words, the result of unsigned multiplication, x, is x = a*b (mod n), and, additionally, we know that x,a,b are in N. It's important to be able to expand many modular formulas like so: x = a*b - k*n, where k is an integer - but in our case x,a,b are in N so this implies that k is in N. Now, let's mathematically say what we're trying to prove: Given positive integers, a,n, and non-negative integers x,b, where x,a,b are in N, and x = a*b (mod n), then a*b >= n (overflow) implies floor(x/a) != b. Proof: If overflow (a*b >= n) then x >= n - k*n = (1 - k)*n (for k in N), As x < n then (1 - k)*n < n, so k > 0. This means x <= a*b - n. So, floor(x/a) <= floor([a*b - n]/a) = floor(a*b/a - n/a) = b - floor(n/a) <= b - 1, Abbreviated: floor(x/a) <= b - 1 Therefore floor(x/a) != b
74,356,070
74,356,191
C++ create an array with type of template base class without specifying the template argument
For example I have some base type Any template<typename T> class Any { public: T data; Any(T data) { this->data = data; } // some other function signatures using data }; class Number : public Any<int> { // functions defining all functions like substracting etc. }; And more classes deriving Any Now in main function I want to create an array of Any int main() { Any types[2] { Number(1), Number(3) }; // doesnt work } Is there another way of doing this?
Let's say you have: class A : public Any<int> { }; class B : public Any<std::string> { }; class C : public Any<double> { }; Objects of type A, B, and C are not subclasses of Any because Any is a template. Rather they are subclasses of Any<int>, Any<std::string> and Any<double>, respectively and as such do not share a common parent class. You may wish to read up on std::variant.
74,356,220
74,356,260
Why is class with std::function argument in constructor not implicitly convertible to callable
Here is a simplified class I have: class Event { private: std::function<void()> m_func; public: Event(std::function<void()> func) : m_func(func) {} }; I cannot do implicit conversions on it: void foo() {} int main() { Event evt = foo; //error evt = []() {}; //error } Why is this? std::function by itself is implicitly convertible to a callable object: std::function<void()> func = []() {}.
Because only one user-defined implicit conversion is allowed in one conversion sequence. For Event evt = foo;, two user-defined conversions are required. One is from function pointer to std::function, one is from std::function to Event. Similarly for evt = []() {};, one user-defined conversion is from lambda to std::function, one is from std::function to Event, are required. You can apply direct initialization instead of copy initialization, or perform some explicit conversion in advance. E.g. Event evt (foo); // direct initialization evt = std::function<void()>([]() {}); // convert lambda to std::function in advance
74,356,368
74,356,489
C++ Reuse Lambda as Compare function in `std::priority_queue`
When working with std::priority_queue, I tried to clear the contents of the priority queue like this: #include <iostream> #include <queue> #include <vector> using std::cout; using std::priority_queue; using std::vector; int main() { const auto comp = [](int a, int b) { return a > b; }; auto a = priority_queue<int, vector<int>, decltype(comp)>(comp); a.push(10); a.push(9); a.push(8); // 3 cout << a.size() << '\n'; a = priority_queue<int, vector<int>, decltype(comp)>(comp); // 0 cout << a.size() << '\n'; return 0; } When compiling with Clang, I got an error: In file included from tmp.cpp:1: /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/c++/v1/queue:455:39: error: no viable overloaded '=' {c = _VSTD::move(__q.c); comp = _VSTD::move(__q.comp); return *this;} ~~~~ ^ ~~~~~~~~~~~~~~~~~~~~~ tmp.cpp:19:7: note: in instantiation of member function 'std::priority_queue<int, std::vector<int>, const (lambda at tmp.cpp:9:23)>::operator=' requested here a = priority_queue<int, vector<int>, decltype(comp)>(comp); ^ tmp.cpp:9:23: note: candidate function (the implicit copy assignment operator) not viable: 'this' argument has type 'std::priority_queue<int, std::vector<int>, const (lambda at tmp.cpp:9:23)>::value_compare' (aka 'const (lambda at tmp.cpp:9:23)'), but method is not marked const const auto comp = [](int a, int b) { ^ 1 error generated. Why would this give me an error? And is there any way to fix it? Thanks.
decltype(comp) is a const type, const auto comp, that makes the priority_queue member variable storing comp to be constant, thus can't be re-assigned. You might want priority_queue<int, vector<int>, remove_cv_t<decltype(comp)>>(comp); Or auto comp = [](int a, int b) { return a > b; }; The copy assignment operator for lambdas are implicitly deleted. The fix: std::function<bool(int, int)> comp = [](int a, int b) { return a > b; };
74,356,948
74,357,140
How do I assign an object to passed nullptr?
Consider the following code: struct MyObject { std::string name; }; void getOrCreateMyObject(std::shared_ptr<MyObject> myObj) { if (myObj == nullptr) { myObj = std::make_shared<MyObject>(); myObj->name = "Created Automatically"; } std::cout << myObj->name << std::endl; } int main() { std::shared_ptr<MyObject> moPtr = nullptr; getOrCreateMyObject(moPtr); if (moPtr != nullptr) { std::cout << moPtr->name << std::endl; } } As you can see, I'm passing a nullptr to the function, where it checks for the nullptr and creates a shared_ptr and successfully uses the newly created object. However, returning back to main, the moPtr is still a nullptr. So how do I make it so I can access that newly object outside the scope of that function? Thank you in advance! Edit: Thank you everybody. Changing the code to void getOrCreateMyObject(std::shared_ptr<MyObject>& myObj) did, of course, work. Somehow I wrongly assumed that passing the pointer automatically resolves to the outer pointer when leaving the function.
Referring to this source: There are two parameter-passing modes in C++: by value,and by reference. When a parameter is passed by value, the changes made to the parameter within the function do not affect the value of the actual argument used in the function call. When a parameter is passed by reference, changes made to the parameter do affect the actual arguments in the client space. In addition, there is a special mode of passing array parameters. So you are passing your parameter by value, which means any changes inside the callee function scope will affect only the copied instance of passed parameter.
74,357,742
74,358,073
Different results of std::isinf for different types and different compilers
Compiling with MSVC(v19.33), this does not compile (C2668 ambiguous call to overloaded function): std::cout << std::isinf(0) << std::endl; But this compiles: std::cout << std::isinf(0.0) << std::endl; However, in cppreference.com, it says: A set of overloads or a function template accepting the arg argument of any integral type. Equivalent to (2) (the argument is cast to double). It seems like the function has existed in the standard since C++11. If I understood correctly, the first code should be equivalent to the second one, shouldn't it? Does this mean MSVC hasn't implemented the overloaded functions yet, or am I missing something? (In contrast, if I use gcc or clang, the above examples compile without problems).
In the Microsoft's implementation, the definition of the isinf is as follows (copied from here): template <class _Ty> _Check_return_ inline bool isinf(_In_ _Ty _X) throw() { return fpclassify(_X) == FP_INFINITE; } The problem with Microsoft's fpclassify is the missing overload for integral types. For more details, see: 'fpclassify': ambiguous call to overloaded function. I agree with the opinion that MSVC is wrong here (however, it seems that they don't care).
74,357,954
74,409,452
Is there documentation for TfLiteTensor available
In the official documentation of tflite API for C++, many methods have TfLiteTensor or a pointer to such type as return value (e.g., input_tensor() method.. Is there any reference to which attributes and methods are available for TfLiteTensor class? I looked in the official Tflite documentation, googled around and went through the source code on github, but couldn't find anything.
TfLiteTensor is part of the TensorFlow Lite C API project and is a C struct (not a c++ class). I'm not seeing any way to generate documentation for it explicitly, nor do I see anything on line. The code API read me is located here: https://github.com/tensorflow/tensorflow/blob/master/tensorflow/lite/c/README.md the TfLiteTensor definition is here: https://github.com/tensorflow/tensorflow/blob/master/tensorflow/lite/c/common.h#L526
74,358,078
74,416,017
Missing binary operator before token "long"
I'm trying to implement FreeRTOS on my Arduino Mega 2560, and during this process, I came across 2 errors that I don't understand. And don't know how to fix. hopefully someone here does. the first error is missing binary operator before token "long". The error points to the following line in FreeRTOSConfig.h: #define configCPU_CLOCK_HZ ((unsigned long) 16000000) And here is the output of the build: C:\Projects\src\config\FreeRTOSConfig.h(36,39): error: missing binary operator before token "long" #define configCPU_CLOCK_HZ ((unsigned long) 16000000) ^ This define is only used in port.c which has another error that I haven't been able to fix. This error comes from the auto-generated makefile. Not sure if these 2 errors are connected, but better add it here if someone knows how to fix it. The error is: recipe for target 'src/Core/FreeRTOS/port.o' failed And this is what I find in the Makefile: src/Core/FreeRTOS/port.o: ../src/Core/FreeRTOS/port.c @echo Building file: $< @echo Invoking: AVR/GNU C Compiler : 5.4.0 $(QUOTE)C:\Program Files (x86)\Atmel\Studio\7.0\toolchain\avr8\avr8-gnu-toolchain\bin\avr-gcc.exe$(QUOTE) -x c -DDEBUG -DBOARD=USER_BOARD -I"C:\Program Files (x86)\Atmel\Studio\7.0\Packs\atmel\ATmega_DFP\1.7.374\include" -I"../src/ASF/common/boards/user_board" -I"../src/ASF/common/boards" -I"../src/ASF/mega/utils/preprocessor" -I"../src/ASF/mega/utils" -I"../src/ASF/common/utils" -I"../src" -I"../src/config" -O1 -fdata-sections -ffunction-sections -fdata-sections -fpack-struct -fshort-enums -mrelax -g3 -Wall -mmcu=atmega2560 -B "C:\Program Files (x86)\Atmel\Studio\7.0\Packs\atmel\ATmega_DFP\1.7.374\gcc\dev\atmega2560" -c -std=gnu99 -fno-strict-aliasing -Wstrict-prototypes -Wmissing-prototypes -Werror-implicit-function-declaration -Wpointer-arith -mrelax -MD -MP -MF "$(@:%.o=%.d)" -MT"$(@:%.o=%.d)" -MT"$(@:%.o=%.o)" -o "$@" "$<" @echo Finished building: $<
missing binary operator before token "long" This error occurs when you try to use the macro in a pre-processor directive. For example, compile the following C++ code: #define configCPU_CLOCK_HZ ((unsigned long) 16000000) #if configCPU_CLOCK_HZ > 0x1000 #endif avr-g++ will complain: *.cpp:1:39: error: missing binary operator before token "long" #define configCPU_CLOCK_HZ ((unsigned long) 16000000) ^ *.cpp:3:5: note: in expansion of macro 'configCPU_CLOCK_HZ' #if configCPU_CLOCK_HZ > 0x1000 ^ So the problem is very likely that configCPU_CLOCK_HZ is used in a pre-prcessor diretcive like above, but configCPU_CLOCK_HZ is not appropriate for such usage. Yet another problem is that the environment that you are using drops a part of the diagnostics. 16000000 is already of type long because it doesn't fit in int, which is 16-bit type in avr-gcc. So in most cases you can just use plain 16000000. If you want something that can be used in preprocessor directives, you can use 16000000ul. Moreover, C99's stdint.h provides macros that yield constants of bit-widths that can be used in preprocessor macros like #include <stdint.h> #define configCPU_CLOCK_HZ UINT32_C(16000000) which will expand to an unsigned 32-bit type. Notice however, that older versions of AVR-LibC had a bug with these macros: It just used casts which does not comply to the language standard, which states that [U]INTXX_C must be usable in pre-precessor macros.
74,358,535
74,358,593
Sorting strings from file to new file
This is my function to get lines from file to strings void getStringsFromFile() { ifstream database; database.open("Database.txt", ios::app | ios::in | ios::binary); if (!database) { cout << "Kunne ikke indlaese filen..." << endl; } int count = 0, c = 0; string getString, tmp, str[256]; for (int i = 0; i < 5; i++) { while (getline(database, getString)) { str[i] = getString; cout << "String: [" << count++ << "] " << str[i] << endl; } } sortStrings(getString); } This is how I'm saving my data to .txt file if (database.is_open()) { database << list[i].navn << "\t" << list[i].addresse << "\t" << list[i].alder << "\t" << list[i].tlf << "\t" << "\n"; database.close(); It outputs like this: line 0 is empty Kasper Jensen Jomfrugade 5 21 44556677 Victor Hansen Østergade 94 25 54644773 I have this function to sort the strings, ascending by insertion. It don't work with string to char void sortStrings(string &lines) { string* lines = nullptr; string temp; int count; for (int i = 0; i < count - 1; i++) { for (int j = 0; j >= 0; j--) { if (lines[j] > lines[j + 1]) { temp = lines[j]; lines[j] = lines[j + 1]; lines[j + 1] = temp; } } } } I want my code to grab relevant lines from one .txt file and sort it to another. I dont really care which sorting method I have problems with it recognizing the right strings and grabbing them and outputting them into new file
The getStringsFromFile function will read all lines from the file, and put them all into str[0]. Then the sortStrings function will attempt to sort a single string. There are other things that looks weird as well. What I recommend you to do, is to create a vector of strings, read lines in a loop (the while (getline(...)) loop) and add to the vector, then use the standard std::sort function to sort the vector. Once that's done you can write the strings in the vector to a new file. Note that the above assume that there's no specific format in the file, that each line is its separate record. If your file have a specific multi-line record format then that won't work. If this is the case then I recommend you create a class for the records, implement a stream extract operator for the class (operator>> for std::istream), and use a loop (while (file >> my_record_object)) to read all records into a vector. Then again sort the vector using std::sort, using a suitable ordering function (lambda or overloaded operator< function for the class). Then write the data in the vector to the new file using an overloaded operator<< function.
74,358,789
74,360,530
Section attribute within template
I'd like to ask why this doesn't relocate the data into the desired section, template <typename T> struct Retram { static T data; inline auto operator=(const T& other) { data = other; return *this; } operator auto &() const { return data; } operator auto *() const { return &data; } }; template <typename T> __attribute__((section(".retram"))) T Retram<T>::data = T(); when this does struct Retram { static int data; inline auto operator=(const int& other) { data = other; return *this; } operator auto &() const { return data; } operator auto *() const { return &data; } }; __attribute__((section(".retram"))) int Retram::data = int(); You are welcome to provide alternate pretty solutions, but I'd still like to understand why this doesn't work. Both compile, but the template version will NOT relocate the symbol as desired. Minimal reproducible example: Retram<int> my_retram_value; my_retram_value = 42; printf("retram value: %i\n", *my_retram_value);
Gcc ignores attributes in templates generally. This is a know bug for many years now. There are more than 10 open bug reports related to this issue. See bugzilla. The problem affects not only member functions but also variable templates and free template functions. Someone has started to work on it but after running in trouble with -flto he gave up. comments for patch Currently it seems that there is nobody interested in fixing this very old issue. Especially for embedded devices this is a real show stopper. This makes it impossible to place templated data to flash or makes it impossible to run interrupt handlers in templated code and much more. People running again on one of the bugs should make a comment in the bug report for the fields "Known to fail" and "Last confirmed". Maybe this makes it visible that the problem persists and the fix is interesting for some more people. But as always in open source projects: Products get better by helping them. I have no experience on gcc development, sorry :-)
74,359,033
74,359,322
Does a object stores lambda function have it's own address?
Based on the result of this topic A lambda which captures no variables (nothing inside the []'s) can be converted into a function pointer I have written a program like void test1(){} int main() { auto test2 = [](){}; printf("%p\n%p\n", test1, &test1); printf("%p\n%p", test2, &test2); return 0; } the result are 0x561cac7d91a9 0x561cac7d91a9 0x7ffe9e565397 (nil) on https://www.programiz.com/cpp-programming/online-compiler/ So the test2 is storing a function pointer to the lambda function? and my question is that object test2, which stores the lambda data, not have its own address? I thought this test2 should have its own address.
Does a object stores lambda function have it's own address? Yes, like all objects in C++ the variable test2 also has a unique address. You can see this by printing &test uisng cout as shown below: int main() { auto test2 = [](){}; std::cout << &test2; //prints address of test2 return 0; } Demo The output of the above modified program is: 0x7ffe4d4b5fcf
74,360,237
74,360,656
Does pthread mutex objects has to be volatile?
I'm learning pthreads after learning about regular threads. Normally when we use a boolean thread object we declare it as a volatile object like this: volatile bool thread_lock;. Do we need to do this on pthread objects as well, specifically on pthread_mutex_t when needed or does it handle it itself? I've looked up into the pthread_mutex_t declaration and found out that it does not have a volatile declaration. Should it be volatile pthread_mutex_t my_obj; or pthread_mutex_t my_obj;
Normally when we use a boolean thread object we declare it as a volatile object like this: volatile bool thread_lock; This use of volatile has never been standard. Some platforms added these semantics to volatile as a regrettable and confusing extension. More tedious details in another answer, but the short version is that you should never use volatile for synchronization. It's neither necessary nor sufficient. The POSIX threading library takes care of everything for you - if you needed to write volatile to make it work, it would say that in its manpages and documentation. It doesn't, because you don't. More portably, C++ has had its own standard concurrency support since 2011, and it's perfectly mature.
74,361,182
74,361,210
CMake - No rule exists to target
In Ubuntu, I have downloaded a third-party shared library (liba1.so), placed in /lib/extern/lib . The associated header files I placed in /lib/extern/include. My own header files are placed in /include/public/ and /include/private/ . And now (to test mylib) I want to link this in my main.cpp code, using CMake. My structure: **My structure:** | | +---CMakeLists.txt | +---lib | | | +---extern | | | +---lib | | | | | +---liba.so | | +---libb.so | | +---liba12.so | | | +---include | | | +...headers.h | +---include | | | +---public | | | | | +---file1.hpp | | +... | | | +---private | | | +---file2.hpp | +... | +---src | +---public | | | +---file1.cpp | +... | +---private | | | +---file2.cpp | +... | +---main.cpp My CMakeLists.txt: cmake_minimum_required(VERSION 3.9...3.19) if(${CMAKE_VERSION} VERSION_LESS 3.12) cmake_policy(VERSION ${CMAKE_VERSION}) endif() project(mylib VERSION 0.0.1 DESCRIPTION "Test" LANGUAGES CXX ) set(CMAKE_CXX_FLAGS "${CMAKE_C_FLAGS} -DTPM_POSIX") set(CMAKE_CXX_STANDARD 20) set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_CXX_EXTENSIONS OFF) add_library(${PROJECT_NAME} STATIC src/private/file2.cpp src/public/file1.cpp ) add_library(lib SHARED IMPORTED) set_target_properties(lib PROPERTIES IMPORTED_LOCATION ${CMAKE_CURRENT_BINARY_DIR}/lib/extern/lib/liba.so) set_target_properties(lib PROPERTIES IMPORTED_LOCATION ${CMAKE_CURRENT_BINARY_DIR}/lib/extern/lib/libb.so) set_target_properties(lib PROPERTIES IMPORTED_LOCATION ${CMAKE_CURRENT_BINARY_DIR}/lib/extern/lib/liba12.so) target_link_libraries(${PROJECT_NAME} PUBLIC lib) target_include_directories(${PROJECT_NAME} PUBLIC $<INSTALL_INTERFACE:lib/extern/include> $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/lib/extern/include> $<INSTALL_INTERFACE:include/public> $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include/public> $<INSTALL_INTERFACE:include/private> $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include/private> ) add_executable(test src/main.cpp) target_link_libraries(test PRIVATE mylib) ERROR: [build] Consolidate compiler generated dependencies of target mylib [build] [ 60%] Built target mylib [build] Consolidate compiler generated dependencies of target test [build] gmake[2]: *** No rule exists to target „lib/extern/lib/liba12.so“, [build] required by „test“ to create. Ending. [build] gmake[1]: *** [CMakeFiles/Makefile2:111: CMakeFiles/test.dir/all] Error 2 [build] gmake: *** [Makefile:91: all] Error 2 [proc] The command: /usr/bin/cmake --build /home/mathew/proj/build --config Debug --target all -j 10 -- exited with code: 2 and signal: null [build] Build finished with exit code 2
Your imported files are relative to the source directory, not the build directory. You need to use CMAKE_CURRENT_SOURCE_DIR instead of CMAKE_CURRENT_BINARY_DIR when setting IMPORTED_LOCATION.
74,361,445
74,368,764
Construct a std::variant out of a boost::variant
I'm trying to construct a std::variant out of a boost::variant. In practice, I'm trying to define a function with the following signature: template <typename... Types> std::variant<Types...> boostvar2stdvar(boost::variant<Types...> input); I've seen the answer to this question, but in that case it's converting a tuple to a std::variant, not a boost::variant. I need my function to take a boost::variant directly. Is there an easy way to do that?
As others have pointed out, you can visit all elements types and return the desired variant from there: template <typename... Types> auto b2std(boost::variant<Types...> const& input) { return boost::apply_visitor( [](auto const& v) -> std::variant<Types...> { return v; }, input); } When used like this auto x = b2std(boost::variant<int, std::string, double>{"hello world"}); Then type of x matches the expected: static_assert( std::is_same_v<std::variant<int, std::string, double>, decltype(x)>); Live See it Live On Coliru #include <boost/variant.hpp> #include <variant> #include <iostream> template <typename... Types> auto b2std(boost::variant<Types...> const& input) { return boost::apply_visitor( [](auto const& v) -> std::variant<Types...> { return v; }, input); } int main() { auto x = b2std(boost::variant<int, std::string, double>{"hello world"}); static_assert( std::is_same_v<std::variant<int, std::string, double>, decltype(x)>); }
74,361,632
74,361,688
error : terminate called after throwing an instance of 'std::bad_alloc' what(): std::bad_alloc;
Why does my code give this bad_alloc error, even though I have allocated enough memory? I'm not able to figure it out. this is the problem link Passing by reference did not resolve the error. #include <bits/stdc++.h> using namespace std; #define ll long long void dfs(ll root , vector<vector<ll>> &graph , vector<ll> &weights , ll max_weight , ll &ans) { for(auto adj : graph[root]) { ans = max(ans , (max_weight - weights[adj]) ); max_weight = max( max_weight , weight[adj]); dfs(adj , graph , weights , max_weight , ans); } } int main() { ll n; cin>>n; vector<ll>a(n+1 , 0); vector<vector<ll>>v(n+1); for(ll i=0 ;i<n;i++) { ll wt;cin>>wt;a[i]=wt; } ll root = -1; for(ll i=0 ;i<n;i++) { ll p;cin>>p; if(p == -1)root = i; v[p-1].push_back(i); } ll ans = INT_MIN; ll wt = a[root]; dfs(root , v , a , wt , ans); cout<<ans<<endl; return 0; }
dfs takes a copy of the vectors graph and a every time it is called recursively, and this probably exhausts your memory. Pass references instead: void dfs(ll root , vector<vector<ll>> const &graph , vector<ll> const &a , ll wt , ll &ans) As a side note: is there a reason you return the result in a reference parameter instead of a return value? To my mind it would be more natural to use ll dfs(ll root , vector<vector<ll>> const &graph , vector<ll> const &a , ll wt) and return ans from dfs.
74,361,724
74,361,799
Append a null terminator to a C++ string
In order to implement a client to some protocol that expects null-byte padding to a specific string, I implemented a functions that pads a string with a specific amount of null bytes: string padToFill(string s, int fill){ int len = s.length(); if (len < fill){ for (int i = 0; i < fill - len; i++){ s.append("\0"); } } return s; } However, in practice, the result I am getting from this function is identical to the string I am getting as argument. So for example padToFill("foo", 5) is foo and not foo\0\0. Even tho c++ strings are expected to handle null bytes as any other character. How do I achieve the desired null padding?
The append overload you're using accepts a C string, which is null-terminated (that is: the first null-byte marks its end). The easiest way here is probably to use a different overload of append: s.append(fill - len, '\0'); Note that this requires C++20. For older C++ standards, there's s.resize(fill, '\0'); or just s.resize(fill); Come to think of it, this may be a clearer way to describe what you're doing, anyway. I like the second option here for clarity.
74,362,449
74,362,914
How to use MPI_Allgatherv on an std::vector of std::vector's?
I have a situation where every MPI process has a nested std::vector that needs to be shared among all other processes with MPI_Allgatherv. Here is a minimal example, where I define a 3x2 nested vector with simple entries (in this case the mpi rank). #include <mpi.h> #include <iostream> #include <vector> int main () { MPI_Init(NULL, NULL); int mpi_processes, mpi_rank; MPI_Comm_size(MPI_COMM_WORLD, &mpi_processes); MPI_Comm_rank(MPI_COMM_WORLD, &mpi_rank); std::vector<std::vector<int>> local_data(3, std::vector<int>(2, mpi_rank)); I would like to combine the local_data vectors to one global vector {{0,0},{0,0},{0,0},{1,1},{1,1},{1,1},...,{mpi_processes,mpi_processes},{mpi_processes,mpi_processes},{mpi_processes,mpi_processes}}. As I understand MPI_Allgatherv should be perfect for this. (In this example all vectors have the same length, but I want to be ready for varying length, hence the Allgatherv and not Allgather.) Therefore, I continue to define a vector for the global data and the necessary input for Allgather, i.e. the receiving count and the displacements. std::vector<std::vector<int>> global_data(mpi_processes*3, std::vector<int>(2)); std::vector<int> recvcounts(mpi_processes, 3); std::vector<int> displs(mpi_processes,0); for(int i = 1; i < mpi_processes; i++) displs[i] = displs[i-1]+ recvcounts[i-1]; Finally, my idea was to define a MPI data type to account for the fact that I have a vector of 2-dim vectors. MPI_Datatype mpi_datapoint; MPI_Type_contiguous(2, MPI_INT, &mpi_datapoint); MPI_Type_commit(&mpi_datapoint); MPI_Allgatherv(local_data.data(), 3, mpi_datapoint, global_data.data(), recvcounts.data(), displs.data(), mpi_datapoint, MPI_COMM_WORLD); MPI_Finalize(); return 0; } This code compiles fine, but when I run it, I get a wall of unhelpful error messages starting with *** Process received signal *** Signal: Abort trap: 6 (6) Signal code: (0) [ 0] 0 libsystem_platform.dylib 0x00007ff80375cc1d _sigtramp + 29 *** Process received signal *** Signal: Abort trap: 6 (6) Signal code: (0) Do you know what is wrong here? And do you know if and how I can use MPI_Allgatherv correctly on a vector of vectors? Thanks in advance for any help on this!
Do you really need all the data gathered together? If so, a vector<vector<>> is usually not a good idea. Instead, wrap the data in a class where you store a single vector, with a 2D indexing function. Or you can use the C++23 mdspan. If you absolutely absolute want that exact structure, you can use MPI_Type_create_hindexed and use the absolute addresses of the .data() parts of the vectors. But I doubt that that's the right solution.
74,363,454
74,363,614
How to minimize protocol buffer memory allocations for large # of messages?
My application uses protocol buffers and has a large number (100 million) of simple messages. Based on callgrind analysis, a memory allocation & deallocation is being made for each instance. Consider the following representative example: // .proto syntax = "proto2"; package testpb; message Top { message Nested { optional int32 val1 = 1; optional int32 val2 = 2; optional int32 val3 = 3; } repeated Nested data = 1; } // .cpp void test() { testpb::Top top; for (int i = 0; i < 100'000; ++i) { auto* data = top.add_data(); data->set_val1(i); data->set_val2(i*2); data->set_val3(i*3); } std::ofstream ofs{"file.out", std::ios::out | std::ios::trunc | std::ios::binary }; top.SerializeToOstream(&ofs); } What is the most effective option for changing the implementation such that the # of memory allocations are not linear with the # of Nested instances?
I would suggest using Arena allocations which were designed for exactly this purpose. https://developers.google.com/protocol-buffers/docs/reference/arenas Memory allocation and deallocation constitutes a significant fraction of CPU time spent in protocol buffers code. By default, protocol buffers performs heap allocations for each message object, each of its subobjects, and several field types, such as strings. These allocations occur in bulk when parsing a message and when building new messages in memory, and associated deallocations happen when messages and their subobject trees are freed. Arena-based allocation has been designed to reduce this performance cost. With arena allocation, new objects are allocated out of a large piece of preallocated memory called the arena. Objects can all be freed at once by discarding the entire arena, ideally without running destructors of any contained object (though an arena can still maintain a "destructor list" when required). This makes object allocation faster by reducing it to a simple pointer increment, and makes deallocation almost free. Arena allocation also provides greater cache efficiency: when messages are parsed, they are more likely to be allocated in continuous memory, which makes traversing messages more likely to hit hot cache lines. To get these benefits you'll need to be aware of object lifetimes and find a suitable granularity at which to use arenas (for servers, this is often per-request). You can find out more about how to get the most from arena allocation in Usage patterns and best practices. This would change your allocations to look more like google::protobuf::Arena arena; testpb::Top* top = google::protobuf::Arena::CreateMessage<testpb::Top>(&arena);
74,363,513
74,369,217
Changing utf encoding in visual studio (C++)
I am making a C++ console program that I would like be able to use some characters from my native language (like š, č, ž, ų, etc.). They all exist in UTF-16 encoding. Is it safe to change my visual studio utf encoding to mentioned UTF-16 and how do I do it properly?
I suggest you to use the following code, it can achieve your needs #include <fcntl.h> #include <io.h> #include <stdio.h> int main() { _setmode(_fileno(stdout), _O_WTEXT); wprintf(L"ščžų"); }
74,364,396
74,364,632
Get vector<Point2f> from cv::Mat
I am getting an input of vector of 2d points, make transformation on them and then output transformed vector of 2d points. My code needs to run fast so I want to optimize memory access time, is there a way to cast rotated_points to vector without copying the data? std::vector<cv::Point2f> points = std::vector<cv::Point2f>({{1, 0}, {0, 1}, {-1, 0}}); auto points_mat= cv::Mat(points); auto rotation_matrix = cv::Matx22f({1, 2, 3, 4}); cv::Mat rotated_points; cv::transform(points_mat, rotated_points, rotation_matrix); std::vector<cv::Point2f> res_vec; res_vec.assign(rotated_points.begin<cv::Point2f>(), rotated_points.end<cv::Point2f>()); I tried to execute the code without copying the data
std::vector<cv::Point2f> res_vec(points.size()); cv::Mat rotated_points(res_vec); cv::transform(points_mat, rotated_points, rotation_matrix); Create vector and pass it as argument to cv::Mat instance with copyData flag set to false (by default it is false cv::Mat ctor). cv::Mat will just refer to vector data as underlying data - cv::Mat will share passed vector's data. All results generated by cv::transform will be stored inside vector by cv::Mat interface.
74,364,607
74,396,151
Qt application hangs on process.start() function. Happens only when function is being called from QML script
I have Embedded Qt applicaiton runing on my HMI screen. I am trying to execute some commands to execute in cmd. I am calling this c++ function simply from QML. Everytime I call it it hangs on process.start(). Do anyone have any experience for such issue? please help. I have ceated a simple function to print out date and it still hangs at process.start() regardless what cmd I execute. cmd.sprintf("date +%%F' '%%X"); qDebug() << "cmd: " << cmd; process.start("sh", QStringList()<<"-c"<<cmd); process.waitForFinished(1000); dtval = process.readAllStandardOutput(); process.close(); I am using Qt 5.9 on Ubuntu 18.04.6LTS platform.
What I found on my side is, the issue was debug mode. If I create release and press the run button (Ctlr + R) then it is absolutely fine (Not the debug button but Run button on QtCreator). Without any changes to my code. I have no idea what that would make the difference on application though.
74,364,674
74,365,865
Make a class befriend a family of functions
I have a class template template <class Key, class T, class Hash, template <class> class Allocator> class Table; and a function template template <class Key, class T, class DevHash, template <class> class DevAllocator, class HostHash, template <class> class HostAllocator> void copyTableToHost(const Table<Key, T, DevHash, DevAllocator> &table, Table<Key, T, HostHash, HostAllocator> &hostTable); Now I want to grant copyTableToHost() access to private members of both table and hostTable. In order to do that I made a friend declaration in Table class: template <class DevHash, template <class> class DevAllocator, class HostHash, template <class> class HostAllocator> friend void copyTableToHost<Key, T, DevHash, DevAllocator, HostHash, HostAllocator>(const Table<Key, T, DevHash, DevAllocator> &table, Table<Key, T, HostHash, HostAllocator> &hostTable); My reasoning is that I don't need to specify Key and T as template parameters here since these are fixed for a given specialization. At the same time a given specialization needs to be friends with a whole class of functions which differ by the choice of DevHash, DevAllocator, HostHash and HostAllocator (I am not sure if template template parameters don't mess things up here ...). The errors I get are of the form member Table<Key, T, Hash, Allocator>::[member name] is inaccessible which makes me believe that the friend declaration didn't work as intended.
If you want it as a free friend function template, one option could be to befriend all instances of it: template <class Key, class T, class Hash, template <class> class Allocator> class Table { template <class K, class Ty, class Hash1, template <class> class Allocator1, class Hash2, template <class> class Allocator2> friend void copyTableToHost(const Table<K, Ty, Hash1, Allocator1>& table, Table<K, Ty, Hash2, Allocator2>& hostTable); int x = 0; // private }; template <class Key, class T, class Hash1, template <class> class Allocator1, class Hash2, template <class> class Allocator2> void copyTableToHost(const Table<Key, T, Hash1, Allocator1>& table, Table<Key, T, Hash2, Allocator2>& hostTable) { hostTable.x = table.x; // now ok } Another option could be to instead use iterators and populate the table in a member function that takes iterators with the requirement they are dereferenced into a std::pair<Key, T> - or whatever class template you are using to package each <Key, T>. It could look like this: #include <type_traits> #include <iterator> template <class Key, class T, class Hash, template <class> class Allocator> class Table { public: template<class It> requires std::is_same_v<typename std::iterator_traits<It>::value_type, std::pair<Key, T>> void copyFrom(It first, It last) { // copy from `first` to `last` } };
74,364,825
74,386,653
UDP port is not free after closesocket call (Windows)
I have two listening sockets (created by calls to socket(AF_INET6, SOCK_DGRAM, IPPROTO_UDP)), at this moment they are maintained from one thread. After creating, they have to be closed (closesocket(...)) and reopened again on the same ports. But bind(...) call returns error 10048 WSAEADDRINUSE on one of these sockets (the second one is opened successfully), and I see by using netstat that the UDP port stays open (closesocket(...) returned no error, SO_REUSEADDR always set to TRUE on all sockets). And this "closed" UDP port stays open as long as the 2nd socket is open (they have no relation, but the "closed" port is closing a second after the 2nd socket is closed). Let's summarize: Open sockets and bind them to ports 8888 and 9999. Close 8888 socket, create new socket, bind it to port 8888 -> success. Close 9999 socket, create new socket, and try to bind it to port 9999 -> error WSAEADDRINUSE. Close 8888 socket -> success. After about a second after #4, port 9999 is freed (by observing in external tool). I have discovered something similar to my problem: https://stackoverflow.com/a/26129726/10101917, but in my case moving all socket operations to one thread does not solve the problem. What is happening here?
I have found what caused this problem. The thing I have programmed is the DLL. I have discovered, that another DLL from this app is using QProcess class of Qt library version 5.7.1. I have checked sources of Qt and discovered that this class actually starts process with bInheritHandles set to TRUE. When I manually have reset this value to FALSE all issues were gone. It is obvious that the issue was caused by the following: one of UDP socket handles was inherited by child process and that process didn't let socket handle to be closed, until that process stop. Thanks to this comment for pointing to the solution.
74,365,968
74,366,031
How to return array of arrays, with different sizes form function
I'm trying to create array of arrays with different sizes and return it, so I can work with it later. Is it even possible? I was trying to do something like this: #include <iostream> int* fun(){ int a[] = {3, 2, 1}; int b[] = {5, 4}; int *arr[] = {a, b}; return *arr; } int main() { int *array = fun(); printf("\n%d, %d, %d", *(array), *(array + 1), *(array + 2)); // this one prints: 3, 2, 1 printf("\t%d, %d", *(array + 3), *(array + 4)); // this one prints random numbers return 0; } I want to access both arrays.
I would refactor to use std::vector instead of c-style arrays #include <iostream> #include <vector> std::vector<std::vector<int>> fun(){ std::vector<int> a{3, 2, 1}; std::vector<int> b{5, 4}; return {a, b}; } int main() { std::vector<std::vector<int>> values = fun(); printf("\n%d, %d, %d", values[0][0], values[0][1], values[0][2]); printf("\t%d, %d", values[1][0], values[1][1]); return 0; }
74,366,093
74,366,268
How to declare simple conversion operator T() in templated base class
I've been working on some class hierarchy with a goal to have a collection of classes that encapsulate primitive types (AdvancedInt, AdvanceDouble, etc.) and give them some additional behavior when accessing their underlaying values, through conversion operator and assignment operator. I can't do this with getters and setter as I can't change the original code and the way it access them, so my only choice is operator overloading. The problem I ran into is with the templated class that defines the conversion operator which gives me a compiler error. Here is the code that illustrates the problem #include <string> class Base { public: Base() = delete; Base(std::string s) : name(s) { //Some extra logic } ~Base() { //More custom logic } virtual std::string get_name() const final { //Final on purpose return name; } private: const std::string name; }; template <typename T, class C> class Serializable :public Base { //Poor man's interface (but not quite) public: Serializable() = delete; Serializable(std::string name) : Base(name) { } operator T() const { //Some extra 'getter' logic return value; } C& operator=(const T& val) { //Some extra 'setter' logic value = val; return (C&)*this; } virtual void serialize() = 0; //This has to be pure virtual private: T value; }; class AdvancedInt final : public Serializable<int, AdvancedInt> { //This is the actual complete class public: AdvancedInt(std::string name) : Serializable(name) { //Nothing here, but needed for the special constructor logic from AbstractBase } void serialize() override { //Some logic here } }; int main() { AdvancedInt adv{"foo"}; int calc = adv; calc += 7; adv = calc; //error C2679 (msvc) | binary '=': no operator found which takes a right-hand operand of type 'int' (or there is no acceptable conversion) return 0; } Now aside from the (probably) questionable practice of passing AdvancedInt to the template of its own base class and it subsequently knowing that it's part of some derived class and implementing its logic (although any feedback on this is welcome), my main question is, what am I doing wrong here? The C& operator=(const T& val) compiles fine when defined as pure virtual, but that enforces the implementation to be in the derived class, and when implemented there with T and C replaced by their corresponding types it works just fine, so the signature is logically sound, but probably not in the correct place(?). From what I've found on cppreference.com, the simple assignment operator is the only assignment operator that cannot be defined outside of class definition. Is this the reason why this code doesn't compile? And if so, is declaring it as pure virtual a way to go?
With adv = calc we look for operator= from AdvancedInt and found (implicit): AdvancedInt& operator=(const AdvancedInt&); AdvancedInt& operator=(AdvancedInt&&); and look-up stops there. Adding: using Serializable<int, AdvancedInt>::operator=; would allow to consider also that overload. And that fixes your issue. Demo.
74,366,357
74,400,482
Updating to Visual Studio 17.4.0 Yields linker errors related to TLS
I just updated my Visual Studio instance from 17.3.6 to 17.4.0. Then I tried a clean build of my solution. Suddenly one of my projects gives me linker errors 8>pch.obj : error LNK2001: unresolved external symbol __imp___tls_index_?init@?1??lazy_init_num_threads@internal@at@@YAXXZ@4_NA 8>pch.obj : error LNK2001: unresolved external symbol __imp___tls_offset_?init@?1??lazy_init_num_threads@internal@at@@YAXXZ@4_NA 8>C:\Users\jmole\Documents\Dev\Main\Solutions\..\Mobile\x64\Debug\net6.0-windows\mld_v143.dll : fatal error LNK1120: 2 unresolved externals This completely confuses me. When I turn on verbose linking I see it finding all sorts of similar symbols in MSVCRTD.lib. For example. 2> Found _tls_index 2> Found __dyn_tls_init Anyone else encountering this?
The name mangling appears to point to at::internal::lazy_init_num_threads, which is a PyTorch function (a bit weird, but it might very well use thread-local storage). You may need to rebuild PyTorch with the same toolchain
74,366,438
74,366,598
c++ function that accepts ostringstream like arguments?
Is there a way in C++ to define a function so that I could do things like this: foo( "Error on line " << iLineNumber ); foo( "name " << strName << " is Invalid" ); as it is now, I'm having to declare an ostringstream object before I call the foo function like this: std::ostringstream strStream1; ostringstream1 << "Error on line " << iLineNumber; foo( ostringstream1 ); std::ostringstream strStream2; ostringstream2 << "name " << strName << " is Invalid"; foo( ostringstream2 );
The compiler is not able to deduce that you want your expression to be converted to std::ostringstream. You can get around this by explicitly providing one to the arguments, which you can do inline with the function : #include <sstream> #include <string> void foo(std::ostringstream osstr) { // Use the stream } int main() { const int iLineNumber = 10; const std::string strName = "file.cpp"; foo( std::ostringstream{} << "Error on line " << iLineNumber ); foo( std::ostringstream{} << "name " << strName << " is Invalid" ); } However, I recommend using a parameter pack and fold expression instead to forward the arguments : #include <sstream> #include <string> #include <utility> // Parameter, variable number of arguments of various types template<class ... T> void foo(T&& ... args) { std::ostringstream stream; // Fold expression, for each argument in args, add it to the stream (stream << ... << std::forward<T>(args)); // Use the stream } int main() { const int iLineNumber = 10; const std::string strName = "file.cpp"; foo( "Error on line ", iLineNumber ); foo( "name ", strName, " is Invalid" ); }