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
72,185,378
72,185,501
Does "new CLASS" return CLASS or CLASS*
This may seem really simple, but I don't know how to actually make a program that tells me this.
As stated in comments, new will always give you a pointer. But as new implies delete, I strongly advise you to take a look at a concept call RAII, especially why it's so popular.
72,185,932
72,191,079
Sorting a list with indexes of another
I am trying to sort a list of indexes based on a list of string, and I receive bellow error - Segmentation fault. I cannot understand why I receive this error and how to solve it? #include <iostream> #include <string.h> using namespace std; int main() { int size = 5; char* mass[size]; int num[size]; for(int i = 0; i < size; i++) { mass[i] = new char[20]; num[i] = i; cin >> mass[i]; } for(int i = 0; i < size; i++){ for(int j = size; j > i; j--) if(strcmp(mass[num[j-1]], mass[num[j]]) > 0){ int tmp = num[j-1]; num[j-1] = num[j]; num[j] = tmp; } } for(int i = 0; i < size; i++){ cout << mass[num[i]] << ", "; } return 0; }
In the inner loop you start with j = size and then num[j] is an out-of-bounds array access. In modern C++ you would solve this like this: #include <iostream> #include <array> #include <algorithm> int main() { const int size = 5; std::array<std::string, size> mass; std::array<int, size> num; for (int i = 0; i < size; i++) { std::cin >> mass[i]; num[i] = i; } std::ranges::sort(num, [mass](int a, int b) { return mass[a] <= mass[b];}); for(int i = 0; i < size; i++){ std::cout << mass[num[i]] << ", "; } std::cout << std::endl; return 0; }
72,186,129
72,190,159
C++ method not calling member method but compiles fine
I'm building a Vulkan Project with CMake and C++. My project compiles fine under MSVC 2019. However, when calling this line: printf("Before\n"); // The below line is where the program hangs. const char** e = this->validationLayers->getRequiredExtensions(); this->createInfo.ppEnabledLayerNames = e; this->createInfo.enabledLayerCount = sizeof(e) / sizeof(e[0]); I get all the outputs for creation of my program up to the "Before" output. The next two lines don't throw a compiler error, but exit my program immediately. Definition const char* const* Dragon::dgVulkanValidationLayer::getRequiredExtensions() { printf("Method"); return this->validationLayers.data(); } Declaration namespace Dragon { class dgVulkanValidationLayer { public: ... const char* const* getRequiredExtensions(); ... private: std::vector<const char*> validationLayers = { "VK_LAYER_KHRONOS_validation" }; }; }; How do I fix this issue? My debugger exits with this line. Exception thrown at 0x00007FF6C2880953 in Exefile.exe: 0xC0000005: Access violation reading location 0xFFFFFFFFFFFFFFFF. EDIT: Clarification. The problem was not in how it was happening. the problem is that when calling the getRequiredExtensions() method the program exits immediately. EDIT 2: So after struggling with my debugger for about a half hour, the line that throws the exception is one inside of the vector.data() method.
enabledLayerCount is the number of elements in the ppEnabledLayerNames array, not the length of the first string. The value you should be assigning is this->validationLayers.size(). Here archive are the spec valid usage requirements for ppEnabledLayerNames and enabledLayerCount. If enabledLayerCount is not 0, ppEnabledLayerNames must be a valid pointer to an array of enabledLayerCount null-terminated UTF-8 strings Additionally the documentation archive for the ppEnabledLayerNames struct member says ppEnabledLayerNames is a pointer to an array of enabledLayerCount null-terminated UTF-8 strings containing the names of layers to enable for the created instance. The layers are loaded in the order they are listed in this array, with the first array element being the closest to the application, and the last array element being the closest to the driver. See the Layers archive section for further details.
72,186,638
72,187,438
Merge similar objects together based on object elements is O(n²). How to make it simpler?
Problem Description We have a vector<A> v containing for 4 objects. Each object has the following members x, y, z and w. Two objects are considered equal if the have the same x and y. In that case we merge the objects: we merge the vector w and we change the value of z if and only if the value of object that we want to check if it exists is different from zero. Else, we consider that it's a new object. In the following source code, I was able to implement the algorithm, but the main issue that it is O(n²) (because I am looping over each object of the vector then using find_if to check if we have a similar object or not in the merged vector). Question Is it possible to make it simpler (that is, less time complexity)? I can't find a way. Source Code #include <iostream> #include <vector> #include <algorithm> class A{ public: int x, y, z; std::vector<int> w; }; int main() { A a1, a2, a3, a4; a1.x = 1; a1.y =2; a1.z = 3; a1.w = {1,2,3,4,5}; a2.x = 4; a2.y =5; a2.z = 6; a2.w = {6,7,8,9}; a3.x = 13;a3.y =14; a3.z = 14; a3.w = {10,11,12}; a4.x = 1; a4.y =2; a4.z = 0;a4.w = {44,45,46,47,48}; std::vector<A> v = {a1, a2, a3, a4}; std::vector<A> merged; /* If 2 objects have the same x and y then merge objects */ for(const A&a:v){ auto it = std::find_if(merged.begin(),merged.end(),[&](const A&ma){ /*2 objects are the same if they have the same x and y*/ return a.x == ma.x and a.y == ma.y; }); /* if 2 objects have the same x and y then merge*/ if(it != merged.end()){ /* Replace z in the merged vector only if a.z is different from 0*/ if(a.z != 0){ it->z = a.z; } /* Merge vectors*/ std::vector<int> mergedws; std::set_union(a.w.begin(),a.w.end(),it->w.begin(),it->w.end(), std::back_inserter(mergedws)); it->w = mergedws; } else { /*We consider that a is a new object, since we couldn't find a similar object in the merged vector*/ merged.push_back(a); } } /* merged vector should have 3 objects because a1 and a4 the same*/ std::cout <<"Number of Objects is: "<< merged.size() << std::endl; for(const auto&m:merged){ std::cout <<"Element "<< m.x <<", "<< m.y <<","<<m.z << std::endl; } return 0; }
You can do it in O(NlogN * MlogM) if you sort the input, and then do a linear pass to merge. N is the length of v, and M is the length of the A::ws. bool compare(const A & lhs, const A & rhs) { return std::tie(lhs.x, lhs.y) < std::tie(rhs.x, rhs.y); } std::sort(v.begin(), v.end(), compare); for (auto first = v.begin(), last = {}; it != v.end(); it = last) { A result = *first; last = std::upper_bound(first++, v.end(), result, compare); for (; first != last; ++first) { if (first->z) { result.z = first->z; } // this is an in-place set_union std::merge(result.w.begin(), result.w.end(), first->w.begin(), first->w.end()); auto unique_end = std::unique(result.w.begin(), result.w.end()); result.w.erase(unique_end, result.w.end()); } merged.push_back(result); }
72,186,671
72,186,924
Is there some way to define a variable as a function such that calling the variable at some given time will return the function's output at that time?
Essentially, I'm trying to do something like #define foobar foo.bar() But without the use of #define, so I can write something along the lines of double foobar = foo.bar(); Obviously, compiling the code above will just define foobar as whatever foo.bar() returns at the time of definition. What I want to do is the above in such a way that using foobar at some time in the code will just use whatever foo.bar() returns at that time, and not whatever it was at definition of foobar.
Obviously, compiling the code above will just define foobar as whatever foo.bar() returns at the time of definition. What I want to do is the above in such a way that using foobar at some time in the code will just use whatever foo.bar() returns at that time, and not whatever it was at definition of foobar. You want a function not a variable: auto foobar() { return foo.bar(); } If foo is not a global (i hope so) and you want to declare the callable on the fly just as you can declare a double, you can use a lambda expression: Foo foo; auto foobar = [&foo](){ return foo.bar(); }; // call it: foobar(); To call the function without the function call syntax () you could use a custom type that calls the function when converted to the returned type. However, as this is non-idiomatic obfuscation, I am not going into more details.
72,187,143
72,187,689
Need Help Understanding OpenMP Matrix Multiplication C++ code
Here is my Matrix Multiplication C++ OpenMP code that I have written. I am trying to use OpenMP to optimize the program. The sequential code speed was 7 seconds but when I added openMP statements but it only got faster by 3 seconds. I thought it was going to get much faster and don't understand if I'm doing it right. The OpenMP statements are in the fill_random function and in the matrix multiplication triple for loop section in main. I would appreciate any help or advice you can give to understand this! #include <iostream> #include <cassert> #include <omp.h> #include <chrono> using namespace std::chrono; double** fill_random(int rows, int cols ) { double** mat = new double* [rows]; //Allocate rows. #pragma omp parallell collapse(2) for (int i = 0; i < rows; ++i) { mat[i] = new double[cols]; // added for( int j = 0; j < cols; ++j) { mat[i][j] = rand() % 10; } } return mat; } double** create_matrix(int rows, int cols) { double** mat = new double* [rows]; //Allocate rows. for (int i = 0; i < rows; ++i) { mat[i] = new double[cols](); //Allocate each row and zero initialize.. } return mat; } void destroy_matrix(double** &mat, int rows) { if (mat) { for (int i = 0; i < rows; ++i) { delete[] mat[i]; //delete each row.. } delete[] mat; //delete the rows.. mat = nullptr; } } int main() { int rowsA = 1000; // number of rows int colsA= 1000; // number of columns double** matA = fill_random(rowsA, colsA); int rowsB = 1000; // number of rows int colsB = 1000; // number of columns double** matB = fill_random(rowsB, colsB); //Checking matrix multiplication qualification assert(colsA == rowsB); double** matC = create_matrix(rowsA, colsB); //measure the multiply only const auto start = high_resolution_clock::now(); //Multiplication #pragma omp parallel for for(int i = 0; i < rowsA; ++i) { for(int j = 0; j < colsB; ++j) { for(int k = 0; k < colsA; ++k) //ColsA.. { matC[i][j] += matA[i][k] * matB[k][j]; } } } const auto stop = high_resolution_clock::now(); const auto duration = duration_cast<seconds>(stop - start); std::cout << "Time taken by function: " << duration.count() << " seconds" << std::endl; //Clean up.. destroy_matrix(matA, rowsA); destroy_matrix(matB, rowsB); destroy_matrix(matC, rowsA); return 0; }
Matrix size of 1000x1000 with double(64 bit) element type requires 8MB data. When you multiply two matrices, you read 16MB data. When you write to a third matrix, you also access 24MB data total. If L3 cache is smaller than 24MB then RAM is bottleneck. Maybe single thread did not fully use its bandwidth but when OpenMP is used, RAM bandwidth is fully used. In your case it had only 50% headroom for bandwidth. Naive version is not using cache well. You need to swap order of two loops to gain more caching: loop loop k loop C[..] += B[..] * A[..] although incrementing C does not re-use a register in this optimized version, it re-uses cache that is more important in this case. If you do it, it should get ~100-200 milliseconds computation time even in single-thread. Also if you need performance, don't do this: //Allocate each row and zero initialize.. allocate whole matrix at once so that your matrix is not scattered in memory. To add more threads efficiently, you can do sub-matrix multiplications to compute full matrix multiplication. Scan-line multiplication is not good for load-balancing between threads. When sub-matrices are multiplied, they give better load distribution due to caching and higher floating-point operations per element fetched from memory. Edit: Swapping order of loops also makes compiler able to vectorize the innermost loop because one of the input matrices becomes a constant during the innermost loop.
72,187,706
72,188,107
makefile, error compiling files from different paths
I have 2 folders, the first folder contains the files I've built, and the second folder contains files I should be using without changing, all the files synchronize and work, already tested by manually compiling them while combined in 1 folder, CC:=g++ COURSE_DIR:=/home/mtm/public/2122b/ HW_DIR:=$(COURSE_DIR)ex2/ OBJS=Card.o Player.o utilities.o Mtmchkin.o test.o EXEC=mtmchkin_test DEBUG_FLAG:=-g -DNDEBUG#assign -g for debug, or -DNDEBUG to turnoff assert HW_FLAG=-I -I$(HW_DIR) COMP_FLAG=--std=c++11 -Wall -pedantic-errors -Werror $(HW_FLAG) $(EXEC) : $(OBJS) $(CC) $(DEBUG_FLAG) $(COMP_FLAG) $(OBJS) -o $@ Card.o : Card.cpp $(HW_DIR)Card.h Player.h $(HW_DIR)utilities.h $(CC) -c $(DEBUG_FLAG) $(COMP_FLAG) $*.cpp -o $@ Player.o : Player.cpp Player.h $(HW_DIR)utilities.h $(HW_DIR)Card.h $(CC) -c $(DEBUG_FLAG) $(COMP_FLAG) $*.cpp -o $@ utilities.o : $(HW_DIR)utilities.cpp $(HW_DIR)utilities.h $(CC) -c $(DEBUG_FLAG) $(COMP_FLAG) $*.cpp -o $@ Mtmchkin.o : Mtmchkin.cpp Mtmchkin.h $(HW_DIR)Card.h Player.h $(HW_DIR)utilities.h $(CC) -c $(DEBUG_FLAG) $(COMP_FLAG) $*.cpp -o $@ test.o : $(HW_DIR)test.cpp Player.h $(HW_DIR)Card.h Mtmchkin.h $(HW_DIR)utilities.h $(CC) -c $(DEBUG_FLAG) $(COMP_FLAG) $*.cpp -o $@ clean: rm -f $(OBJS) $(EXEC) The makefile is in the first folder as I mentioned, and the HW_DIR is the path to the 2nd folder I mentioned, but it doesn't compile. Any idea on what the problem is and how I can fix it? Edit: This is the input I've made from the first folder i mentioned and contains the makefile and output [final]$ make g++ -c -g -DNDEBUG --std=c++11 -Wall -pedantic-errors -Werror -I -I/home/mtm/public/2122b/ex2/ Card.cpp -o Card.o Card.cpp:1:18: fatal error: Card.h: No such file or directory #include "Card.h" ^ compilation terminated. make: *** [Card.o] Error 1 I want to it to compile successfully and put the exec file in the same folder as the makefile.
Your problem appears to be: HW_FLAG=-I -I$(HW_DIR) This sets the include path to -I/home/mtm/public/2122b/ex2/ which (as a relative path, since it begins with -) would be a (presumably nonexistent) directory under the current directory. it should be: HW_FLAG=-I $(HW_DIR) GCC's command line documentation shows that -I can have a space before its argument. Also, make sure that all of the different folders where your include files live are represented in the include path. If (as it appears) there are .h files in the same folder as the makefile, you can try -I . -I $(HW_DIR) However, you may need to specify the full path to the makefile instead of . Finally, $* won't work for compiling $(HW_DIR)utilities.cpp and $(HW_DIR)test.cpp because they're in a different directory from the targets utilities.o and test.o. (documentation link). Just use e.g. $(HW_DIR)\utilities.cpp explicitly for that rule, instead of $*.cpp.
72,187,797
72,189,169
How to generate CRC7 based on lookup table?
I am trying to implement CRC-7/MMC checksum with pregenerated lookup table. This is the code so far: #include <iostream> #include <string> #include <cstdint> using namespace std; /* CRC-7/MMC Poly: 0x09 Xorout: NO Init: 0x00 Check value: 0x75 for "123456789" */ uint16_t CRC7_table[256]; void generate_crc7_table() { uint16_t byte; for (uint16_t i = 0; i < 256; i++) { byte = i; for (uint16_t bit = 0; bit < 8; bit++) { if (byte & 1) { //if lsb is 1 byte >>= 1; byte ^= 0x09; } else byte >>= 1; } CRC7_table[i] = byte >> 1; //to drop off MSB } } uint16_t crc7(string input) { uint16_t reg = 0; uint16_t b; for (uint16_t i = 0; i < input.length(); i++) { b = (input[i] ^ reg) & 0xFF; reg = (reg >> 1) ^ CRC7_table[b]; } return reg; } int main() { generate_crc7_table(); cout << hex << crc7("123456789") << endl; return 0; } But it gives wrong output. I should get 0x75 but I get 0x07. I used this website to checkout the outputs. Any suggestion or idea is highly appreciated. Thanks.
Note that the CRC definition you pointed to includes refin=false refout=false. That CRC is not reflected, so it is computed with left shifts, not right shifts. Given that, and the fact that the CRC is less than eight bits in length, you will also want to keep the seven bits at the top of the byte being used for calculation, as opposed to the bottom. I.e. bits 1 to 7, as opposed to bits 0 to 6. The polynomial is then also shifted up by one for the table calculation. This allows the table-driven, byte-wise calculation to simply exclusive-or each message byte into the byte being used for the calculations. If you want to return the CRC in the low seven bits, you can shift it down one at the end. Example (0x12 is 0x09 shifted up one): #include <iostream> #include <string> uint8_t table[256]; void make_table() { uint8_t octet = 0; do { uint8_t crc = octet; for (int k = 0; k < 8; k++) crc = crc & 0x80 ? (crc << 1) ^ 0x12 : crc << 1; table[octet++] = crc; } while (octet); } uint8_t crc7(std::string const& input) { uint8_t crc = 0; for (auto octet : input) crc = table[crc ^ octet]; return crc >> 1; } int main() { make_table(); std::cout << std::hex << (unsigned)crc7("123456789") << '\n'; } crcany will generate CRC code for you, given the definition. Since your CRC-7/MMC is in Greg's catalogue, crcany will generate that code out of the box, along with the other 100+ CRCs defined there. The generated code includes bit-wise, byte-wise, and word-wise calculations.
72,187,895
72,188,038
Is passing literal string as template parameter not good
I'm working on a c++ project and I just defined a function as below: template<typename... Args> void func(Args&&... args) {} Then, call it like this: func("abc"); // char[4]? func("de"); // char[3]? My question is if the compiler will deduce two independent functions, one is for char[4] and the other is for char[3]? If I call many func with const char* as above, the compiler will generate many independent functions? Is this stupid? Should I avoid this? In fact, func("abc") and func(std::string("abc")); are exactly the same for me. So should I call this function like func(std::string("abc")); and func(std::string("de")); so that the compiler will generate only one function as void func(const std::string&); BTW, My project is developed with C++14.
My question is if the compiler will deduce two independent functions, one is for char[4] and the other is for char[3]? It will. If I call many func with const char* as above, the compiler will generate many independent functions? You don't call func with const char*. If you did call func with only const char* then there would be only one instantiation of the function template. You call the function with const char[4] and const char[3] which do cause separate instantiations. There will be an instantiation for each unique sets of template arguments. Is this stupid? Should I avoid this? Depends on use case. In many cases, the optimiser simply expands all calls inline and the instantiations won't leave any trace of their theoretical existance in the generated assembly.
72,188,061
72,188,786
Why does new int() work like an array in C++?
As far as I understand int* p = new int(); Is something like creating an int with a constructor. If so why does the following code work like an array? int* p = new int(); *p = 5; p[1] = 15; for (int i = 0; i < 2; i++) cout << p[i] << endl; 5 15
Why does new int() work like an array in C++? p[1] is equivalent to *(p + 1), it simply dereferences the pointer to access the value stored in the memory location where it points to, the notation is similar to array notation, it's allowed and is preferred to pointer notation because it's more readable. As far as I understand int* p = new int(); Is something like creating an int with a constructor. Yes, but that's not all, you are also allocating memory for exactly one int and assigning the memory address to the pointer p. Note that it could be int* p = new int[2], it's the exact same pointer, but in this case the memory block returned by new is good for 2 int instead of just the one, incidentally this would make the rest of your code valid, except for the fact that you do not delete the memory allocated by new, which would cause a memory leak. Now consider the following code: int arr[10]; int* p = arr; In this case you have the exact same pointer, but it will be pointing to the first element of an array with automatic storage duration. The pointer does not know how much memory it points to because it's pointing to the first element in a given memory block, for the program it's not apparent how big that block is. When indexing the pointer, it's the programmer responsability to not overrun that memory. One important thing to note is that, in some cases, where other languages might stop you from putting your foot in it, C++ does not, it trusts the programmer to produce correct code, that's why it's usually harder to be a C++ programmer. As already pointed out your program incurs in undefined behavior while accessing p[1]. Note the first phrase of the linked resource, it simply states: [Undefined behavior] renders the entire program meaningless if certain rules of the language are violated That is the case here, the memory you are accessing is located out of the bounds defined by your manual memory allocation. The fact that the output is what you expect is a matter of (bad, I would say) luck, it may output the correct result today and crash tomorrow, who knows. You can see by the above examples that this situation would be hard to diagnose, it's the exact same type for the 3 sample cases. In any case there are ways to diagnose memory problems like this, examples are valgrind and gcc address sanitizer, among others. On a side note, avoid using raw pointers, use smart pointers or one of the C++ containers if possible. I would also encourage you to acquire some knowledge on the related topic of OOP RAII principles.
72,188,255
72,271,889
How can I make sure `iostream` is available to the linker?
I have the following C++ code in a file called helloworld.cpp: #include<iostream> int main() { std::cout << "Hello, World!\n"; } I would like to compile this manually so I can really understand how the compilation steps work with gcc, namely: Preprocessing Compilation Assembly Linking This article gives some useful information about how to break up the compilation steps. And so I came up with the following: Preprocessing cpp helloworld.cpp > helloworld.i Compilation g++ -S helloworld.i Assembly as -o helloworld.o helloworld.s Linking ld -o helloworld helloworld.o Everything seems to work except for the last step, as outlined by the article: ld -o hello hello.o ...libraries... The libraries argument above is a long list of libraries that you need to find out. I omitted the exact arguments because the list is really long and complicated, and depends on which libraries g++ is using on your system. If you are interested to find out, you can run the command g++ -Q -v -o hello hello.cpp and take a look at the last line where g++ invokes collect2 And so I tried running g++ -Q -v -o helloworld helloworld.cpp, but the result is extremely verbose. I'm still unsure how to complete ld such that iostream can be available to the linker when I invoke it. How can I make sure iostream is available to the linker?
Based on the comments and posted answer I realized that the blog from which I was copying those commands makes things more complicated than they really need to be for my purposes. It's definitely possible to isolate every step of the compilation process using solely the g++ command. Here's a Makefile I came up with: all: preprocess compile assemble link # helloworld.i contains preprocessed source code preprocess: @echo "\nPREPROCESSING\n"; g++ -E -o helloworld.i helloworld.cpp # compile preprocessed source code to assembly language. # hello.s will contain assembly code compile: @echo "\nCOMPILATION\n"; g++ -S helloworld.i # convert assembly to machine code assemble: @echo "\nASSEMBLY\n"; g++ -c helloworld.s # links object code with the library code to produce an executable # libraries need to be specified here link: @echo "\nLINKING\n"; g++ helloworld.o -o test clean: @find -type f ! -name "*.cpp" ! -name "*.h" ! -name "Makefile" -delete Now I can compile my C++ programs in such a way that I can track whether the preprocessor, compiler, assembler or linker is generating the error.
72,188,334
72,334,146
What is a "container detachement" in the C++11 ranged based loop over QList? Is it a performance only problem?
This question contains some proposals for working around the problem, I would like to understand more in depth that exactly the problem is: QList<QString> q; for (QString &x: q) { .. } Is it so that unless the container is declared const, Qt makes a copy of the list and then iterates over that copy? This is not among the best, but would be bearable if the list is small (say 10-20 QString's). Is it performance only problem or it can be some deeper problem? Let's assume we do not add/remove elements while the loop is running. Is the modification of the value in the loop (assuming it is a reference) something that still works or it is fundamentally broken?
Copy-on-write (=Implicit sharing) concept It is important to understand that copy-on-write (= implicit shared) classes externally behaves like "normal" classes that perform a deep copy of their data. They only postpone this (potentially) expensive copy operation as long as possible. A deep copy is made (=detaching), only if the following sequence occurs: The list is implicitly shared, i.e. the object is copied by value (and at least 2 instances still exist) A non-const member function is accessed on the implicitly shared object. Your questions Only if the container is shared (by another copy on write instance of this list), a copy of the list will be made (as a non-const member is invoked on the list object). Note that the C++ range loop is just a short hand for a normal iterator based for loop (see [1] for the exact equivalence which depends on the exactly used C++ version): for (QList<QString>::iterator& it = q.begin(); x != q.end(); ++it) { QString &x = *it; ... } Note that the begin method is a const member function if and only if the list q itself is declared const. If you would write it in full yourself, you should use constBegin and constEnd instead. So, QList<QString> q; q.resize(10); QList<QString>& q2 = q; // holds a reference to the same list instance. Modifying q, also modifies q2. for (QString &x: q) { .. } doesn't perform any copy, as list q isn't implicitly shared with another instance. However, QList<QString> q; q.resize(10); QList<QString> q2 = q; // Copy-on-write: Now q and q2 are implicitly shared. Modifying q, doesn't modify q2. Currently, no copy is made yet. for (QString &x: q) { .. } does make a copy of the data. This is mostly a performance issue. Only if the list contain some special type with a weird copy constructor/operator, this may be not the case, but this would probably indicate a bad design. In rare cases, you may also encounter the Implicit sharing iterator problem, by detaching (i.e. deep copy) a list when an iterator is still active. Therefore, it is good practice to avoid unneeded copies in all circumstances by writing: QList<QString> q = ...; for (QString &x: qAsConst(q)) { .. } or const QList<QString> q = ...; for (QString &x: q) { .. } Modifications in the loop aren't broken and work as expected, i.e. they behave as if the QList doesn't use implicit sharing, but performs a deep copy during a copy constructor/operator. For example, QList<QString> q; q.resize(10); QList<QString>& q2 = q; QList<QString> q3 = q; for (QString &x: q) {x = "TEST";} q and q2 are identical, all containing 10 times "TEST". q3 is a different list, containing 10 empty (null) strings. Also check the Qt documentation itself about Implicit Sharing, which is used extensively by Qt. In modern C++, this performance optimization construct could be (partially) replaced by newly introduced move concept. Improve understanding by inspecting source code Every non-const function calls detach, before actually modifying the data, f.ex. [2]: inline iterator begin() { detach(); return reinterpret_cast<Node *>(p.begin()); } inline const_iterator begin() const noexcept { return reinterpret_cast<Node *>(p.begin()); } inline const_iterator constBegin() const noexcept { return reinterpret_cast<Node *>(p.begin()); } However, detach only effectively detaches/deep copy the data when the list is actually shared [3]: inline void detach() { if (d->ref.isShared()) detach_helper(); } and isShared is implemented as follows [4]: bool isShared() const noexcept { int count = atomic.loadRelaxed(); return (count != 1) && (count != 0); } i.e. more than 1 copy (= another copy except for the object itself) exists.
72,188,544
72,188,571
error: expected unqualified-id before ‘friend’
In my .cpp file I got Student:: friend istream& operator>>(istream &input,Student &a){ input>>a.AM>>a.name>>a.semester>>; return input; } And in my .h file I got friend istream &operator>>(istream &input,Student &a); I keep getting that error and I don't know what to do.Any help?
Rewrite the definition like istream& operator>>(istream &input,Student &a){ input>>a.AM>>a.name>>a.semester>>; return input; } The specifier friend is used only in a declaration of a friend function within a class. And a friend function is not a member of the class granting friendship.
72,188,762
72,189,678
Can I replace an if-statement with AND?
My prof once said, that if-statements are rather slow and should be avoided as much as possible. I'm making a game in OpenGL, where I need a lot of them. In my tests replacing an if-statement with AND via short-circuiting worked, but is it faster? bool doSomething(); int main() { int randomNumber = std::rand() % 10; randomNumber == 5 && doSomething(); return 0; } bool doSomething() { std::cout << "function executed" << std::endl; return true; } My intention is to use this inside the draw function of my renderer. My models are supposed to have flags, if a flag is true, a certain function should execute.
I agree with the comments above that in almost all practical cases, it's OK to use ifs as much as you need without hesitation. I also agree that it is not an issue important for a beginner to waste energy on optimizing, and that using logical operators will likely to emit code similar to ifs. However - there is a valid issue here related to branching in general, so those who are interested are welcome to read on. Modern CPUs use what we call Instruction pipelining. Without getting too deap into the technical details: Within each CPU core there is a level of parallelism. Each assembly instruction is composed of several stages, and while the current instruction is executed, the next instructions are prepared to a certain degree. This is called instruction pipelining. This concept is broken with any kind of branching in general, and conditionals (ifs) in particular. It's true that there is a mechanism of branch prediction, but it works only to some extent. So although in most cases ifs are totally OK, there are cases it should be taken into account. As always when it comes to optimizations, one should carefully profile. Take the following piece of code as an example (similar things are common in image processing and other implementations): unsigned char * pData = ...; // get data from somewhere int dataSize = 100000000; // something big bool cond = ...; // initialize some condition for relevant for all data for (int i = 0; i < dataSize; ++i, ++pData) { if (cond) { *pData = 2; // imagine some small calculation } else { *pData = 3; // imagine some other small calculation } } It might be better to do it like this (even though it contains duplication which is evil from software engineering point of view): if (cond) { for (int i = 0; i < dataSize; ++i, ++pData) { *pData = 2; // imagine some small calculation } } else { for (int i = 0; i < dataSize; ++i, ++pData) { *pData = 3; // imagine some other small calculation } } We still have an if but it's causing to branch potentially only once. In certain [rare] cases (requires profiling as mentioned above) it will be more efficient to do even something like this: for (int i = 0; i < dataSize; ++i, ++pData) { *pData = (2 * cond + 3 * (!cond)); } I know it's not common , but I encountered specific HW some years ago on which the cost of 2 multiplications and 1 addition with negation was less than the cost of branching (due to reset of instruction pipeline). Also this "trick" supports using different condition values for different parts of the data. Bottom line: ifs are usually OK, but it's good to be aware that sometimes there is a cost.
72,188,924
72,189,239
C++ Segmentation fault when changing value of pointer within method call
I'm programming a server - client application with a shared utils.cpp. So the server and client use the (in utils.h) predefined methods: int listening_socket(int port); int connect_socket(const char *hostname, const int port); int accept_connection(int sockfd); int recv_msg(int sockfd, int32_t *operation_type, int64_t *argument); int send_msg(int sockfd, int32_t *operation_type, int64_t *argument); So far, so good. But since the recv_msg() just returns if it was successful or not I need to handle the transmitted operation_type and argument via pointer modification. At this point I am kind of lost. My goal is to set the method parameters (the int32_t *operation_type and int64_t *argument pointer) to the transmitted values. In server.cpp I have initialised the int32_t * and int64_t * in order to pass them into the recv_msg() method (also tried to give them a value e.g. = 0). server.cpp: ... int32_t *operation_type; // with = 0; also Segmentation fault int64_t *operation_type; // with = 0; also Segmentation fault if (recv_msg(server_socket, operation_type, argument) == 0) printf("In server.cpp: operation_type: %" PRId32 " and argument: %" PRId64 " \n", operation_type, argument); In utils.cpp the method I am trying to change the pointer's value via: int recv_msg(int sockfd, int32_t *operation_type, int64_t *argument) { // some buffer and read() stuff... // trying to change pointer's value operation_type = (int32_t *)1; // also tried *operation_type = 1; // and same thing with the int64_t * argument pointer int64_t argu = message.argument(); // also tried this *argument = argu; printf("In utils.cpp: operation_type: %" PRId32 " and argument: %" PRId64" \n", operation_type, argument); Ether I don't change the points values, so in method they have the wanted value, but after executing the recv_msg() the points value is 0 again or I get a Segmentation fault. I understand the basics of pointers and references, but I am used to Java and new to the "*" and "&" prefixes. My question: How do I can modify pointers which are passed as parameters in a imported method, or I am ready the int32_t and int64_t wring?
Pointers are variables that should be use to point to some allocated memory. In your initialization, you made your pointers point to NULL, i.e, no memory. And after that you are trying to change the value of nothing. That's why you are getting a segmentation fault. You should either: Declare some local variables and make your pointers point to them. Something like: int32_t local_type_operation; type_operation = &local_type_operation; Or use some dynamic memory allocation function to allocate some memory to point to (search about malloc).
72,189,469
72,189,929
Embedding Python to C++ Receiving Error Segmentation fault (core dumped)
This is my first go at Embedding Python in C++. I am just trying to create a simple program so I understand how it works. The following is my code. main.cpp #define PY_SSIZE_T_CLEAN #include </usr/include/python3.8/Python.h> #include <iostream> int main(int argc, char *argv[]){ PyObject *pName, *pModule, *pFunc, *pArgs, *pValue; Py_Initialize(); pName = PyUnicode_FromString((char*)"script"); pModule = PyImport_Import(pName); pFunc = PyObject_GetAttrString(pModule, (char*)"test"); pArgs = PyTuple_Pack(1, PyUnicode_FromString((char*)"Greg")); pValue = PyObject_CallObject(pFunc, pArgs); auto result = _PyUnicode_AsString(pValue); std::cout << result << std::endl; Py_Finalize(); } script.py def test(person): return "What's up " + person; This is how I have been compiling on Linux g++ -I/usr/include/python3.8/ main.cpp -L/usr/lib/python3.8/config-3.8-x86_64-linux-gnu -lpython3.8 -o output I am compiling like this because (#include <Python.h> has been giving me troubles, Yes I have tried sudo apt-get install python3.8-dev) The file compiles successfully but when I try to run ./output I receive the following error. Segmentation fault (core dumped) I searched up what this error means and it is saying that Segmentation fault is a specific kind of error caused by accessing memory that “does not belong to you.” But which memory does not belong to me? Is it the python file? Any Guidance would be much appreciated.
After each and every one of those statements, you will need to check for errors, using something of the form: if (varname == NULL) { cout << “An error occured” << endl; PyErr_Print(); return EXIT_FAILURE; } This will check if the python layer through an error; and if so will ask it to print the Python traceback to the screen, and exit. You can use this traceback to figure out what your error is. Any of those functions can fail, and you need to check for failure before you continue. Using the Python C API is extremely fiddly because of this. Most C API functions that return a pointer return NULL on error, and passing NULL into any function without checking it first is bound to result in a crash. You get a segmentation fault from accessing a NULL pointer, as nearly all modern systems map access of NULL to a segmentation fault or crash of some sort to catch programming errors.
72,189,626
72,189,823
simplest way to prevent accesing array beyond range in C
I'm wondering if there is any easier way to prevent accessing array beyond range than using if() statement. I have switch case code for arduino like this with many cases: switch(a){ case 3: case 27: for (int i = 0; i < 8; i++){ leds[ledMapArray[x][i]] = CRGB(0,255,0); leds[ledMapArray[i][y]] = CRGB(0,255,0); if ((x + i < 8) && (y + i < 8)) leds[ledMapArray[x + i][y + i]] = CRGB(0,255,0); if ((x - i >= 0) && (y - i >= 0)) leds[ledMapArray[x - i][y - i]] = CRGB(0,255,0); if ((x + i < 8) && (y - i >= 0)) leds[ledMapArray[x + i][y - i]] = CRGB(0,255,0); if ((x - i >= 0) && (y + i < 8)) leds[ledMapArray[x - i][y + i]] = CRGB(0,255,0); } break; case 4: case 28: if (x + 1 < 8) leds[ledMapArray[x + 1][y]] = CRGB(0,255,0); if (x - 1 >= 0) leds[ledMapArray[x - 1][y]] = CRGB(0,255,0); if (y - 1 >= 0) leds[ledMapArray[x][y - 1]] = CRGB(0,255,0); if (y + 1 < 8) leds[ledMapArray[x][y + 1]] = CRGB(0,255,0); if ((x + 1 < 8) && (y + 1 < 8)) leds[ledMapArray[x + 1][y + 1]] = CRGB(0,255,0); if ((x - 1 >= 0) && (y - 1 >= 0)) leds[ledMapArray[x - 1][y - 1]] = CRGB(0,255,0); if ((x + 1 < 8) && (y - 1 >= 0)) leds[ledMapArray[x + 1][y - 1]] = CRGB(0,255,0); if ((x - 1 >= 0) && (y + 1 < 8)) leds[ledMapArray[x - 1][y + 1]] = CRGB(0,255,0); break; ... ledMapArray is 8x8 array where x and y value may be <7,0>. Here are some definitions: // CRGB is structure from FastLed library CRGB leds[NUM_LEDS]; // from FastLed library to control LED strip // Array to show how LED strip looks like, values in array represents leds const short ledMapArray[8][8] = {{0, 1, 2, 3, 4, 5, 6, 7}, {15, 14, 13, 12, 11, 10, 9, 8}, {16, 17, 18, 19, 20, 21, 22, 23}, {31, 30, 29, 28, 27, 26, 25, 24}, {32, 33, 34, 35, 36, 37, 38, 39}, {47, 46, 45, 44, 43, 42, 41, 40}, {48, 49, 50, 51, 52, 53, 54, 55}, {63, 62, 61, 60, 59, 58, 57, 56}}; The point of this switch case is to light up specific LEDs from LED strip. I want to show allowed moves for chess pieces on smart chessboard. Is there any better way to do this?
The Answer was written when the question used the tag c, not c++ and edited later. The FastLED library is clearly implemented in C++. You could wrap the array access in a function that implements the checks. The following function assumes that the array leds and ledMapArray are file scope variables. Otherwise the function would need more arguments. In C++, the function will also work if the function and the variables are members of the same class. Instead of a hard-coded number 8, the check should better be implemented based on the number of elements in the array. (Something like sizeof(array)/sizeof(array[0]). I would need to see the definition of leds and ledMapArray.) Note that the function implements a bounds check for ledMapArray only, not for leds. void setLed(int x, int y, some_type crgb) { if((x >= 0) && (x < 8) && (y >= 0) && (y < 8)) { leds[ledMapArray[x][y]] = crgb; } } The function could also be replaced with a macro which would work for local array variables as well as for global variables. #define setLed(x, y, crgb) do { \ if((x >= 0) && (x < 8) && (y >= 0) && (y < 8)) { \ leds[ledMapArray[x][y]] = crgb; \ } \ } while(0) switch(x){ case 3: case 27: for (int i = 0; i < 8; i++){ setLed(x, i, CRGB(0,255,0)); setLed(i, y, CRGB(0,255,0)); setLed(x + i, y + i, CRGB(0,255,0)); setLed(x - i, y - i, CRGB(0,255,0)); setLed(x + i, y - i, CRGB(0,255,0)); setLed(x - i, y + i, CRGB(0,255,0)); } break; case 4: case 28: setLed(x + 1, y, CRGB(0,255,0)); /* etc ... */ Instead of repeatedly using anonymous objects with the same constructor CRGB(0,255,0), you could use a named object. CRGB greenColor(0,255,0); setLed(x, i, greenColor); setLed(i, y, greenColor); /* etc ... */ Or use pre-defined color objects from the library. setLed(x, i, CRGB::Green); setLed(i, y, CRGB::Green); /* etc ... */
72,190,379
72,249,840
lld runs LTO even if -fno-lto is passed
I have a CMake project with several subprojects that create static libraries built with -flto=thin. The project has a lot of tests that are linked against the aforementioned libraries. With LTO it takes a lot of time to build tests, therefore I have disabled LTO for tests using -fno-lto. What I noticed though, is that lld performs LTO on tests even with -fno-lto. If I run the linker with --time-trace I can see that the majority of the time is spent on LTO. My questions are: Is this expected? If so I can assume that lld performs LTO whenever it finds the LTO info in the object it links. If not, is there a way to disable this behavior? Adding -fno-lto to the compiler does not seem to work, and lld does not have a param to explicitly disable LTO. If not, is this a bug? Update 1: This is how I handle lto in CMake: # Enable Thin LTO only on non-test targets. if(ENABLE_LTO) if (IS_TEST) target_compile_options(${TARGET} PRIVATE -fno-lto) # Probably pointless. target_link_options(${TARGET} PRIVATE -fno-lto) else() message(STATUS "ENABLE_LTO on target ${TARGET})") target_compile_options(${TARGET} PRIVATE -flto=thin) target_link_options(${TARGET} PRIVATE -flto=thin -Wl,--thinlto-cache-dir=${CMAKE_BINARY_DIR}/lto.cache) endif() endif()
If you compile the libraries with -flto then, at least for gcc, the object files will only contain the intermediate language and no binary code. That means when you link them into your test cases compiled with -fno-lto there is no binary code to link to. The linker has no choice but to first compile the intermediate language into binary for each needed function, which you would see as an LTO phase. In gcc there is an option -ffat-lto-objects that tells gcc to include both the intermediate language as well as binary code in the object files. They can then be used for linking with LTO or without. The drawback is that this takes a bit longer to compile and produces larger object files. You have to check if clang has the same option, they are usually pretty compatible with options.
72,190,405
72,191,099
Switching between threads with C++20 coroutines
There is an example of switching to a different thread with C++20 coroutines: #include <coroutine> #include <iostream> #include <stdexcept> #include <thread> auto switch_to_new_thread(std::jthread& out) { struct awaitable { std::jthread* p_out; bool await_ready() { return false; } void await_suspend(std::coroutine_handle<> h) { std::jthread& out = *p_out; if (out.joinable()) throw std::runtime_error("Output jthread parameter not empty"); out = std::jthread([h] { h.resume(); }); // Potential undefined behavior: accessing potentially destroyed *this // std::cout << "New thread ID: " << p_out->get_id() << '\n'; std::cout << "New thread ID: " << out.get_id() << '\n'; // this is OK } void await_resume() {} }; return awaitable{ &out }; } struct task { struct promise_type { task get_return_object() { return {}; } std::suspend_never initial_suspend() { return {}; } std::suspend_never final_suspend() noexcept { return {}; } void return_void() {} void unhandled_exception() {} }; }; task resuming_on_new_thread(std::jthread& out) { std::cout << "Coroutine started on thread: " << std::this_thread::get_id() << '\n'; co_await switch_to_new_thread(out); // awaiter destroyed here std::cout << "Coroutine resumed on thread: " << std::this_thread::get_id() << '\n'; } int main() { std::jthread out; resuming_on_new_thread(out); } the coroutine starts on the main thread and switches to a newly created thread. What is the right way to make it switch back to the main thread? So the code below task resuming_on_new_thread(std::jthread& out) { std::cout << "Coroutine started on thread: " << std::this_thread::get_id() << '\n'; co_await switch_to_new_thread(out); // awaiter destroyed here std::cout << "Coroutine resumed on thread: " << std::this_thread::get_id() << '\n'; co_await switch_to_main_thread(); std::cout << "Coroutine resumed on thread: " << std::this_thread::get_id() << '\n'; } would print Coroutine started on thread: 139972277602112 New thread ID: 139972267284224 Coroutine resumed on thread: 139972267284224 Coroutine resumed on thread: 139972277602112
switch_to_new_thread actually creates a new thread, it doesn't switch to a new thread. It then injects code that resumes the coroutine in it. To run code on a specific thread, you have to actually run code on that thread. To resume a coroutine, that specific thread has to run code that resume that coroutine. Here you did it by creating a brand-new thread and injecting code that does a resume. A traditional way to do stuff like this is with a message pump. The thread you want to participate has a message pump and a queue of events. It runs the events in order. To make a specific thread run some code, you send a message to that queue of events with the instructions (maybe the actual code, maybe just a value) in it. To this end, such an "event consuming thread" is more than a std::jthread or std::thread; it is a thread safe queue and some in the thread popping tasks off it an executing them. In such a system, you'd move between threads by sending messages. So you'd have a queue: template<class T> struct threadsafe_queue { [[nodiscard]] std::optional<T> pop(); [[nodiscard]] std::deque<T> pop_many(std::optional<std::size_t> count = {}); // defaults to all [[nodiscard]] bool push(T); template<class C, class D> [[nodiscard]] std::optional<T> wait_until_pop(std::chrono::time_point<C,D>); void abort(); [[nodiscard]] bool is_aborted() const { return aborted; } private: mutable std::mutex m; std::condition_variable cv; std::deque<T> queue; bool aborted = false; auto lock() const { return std::unique_lock(m); } }; of tasks: using task_queue = threadsafe_queue<std::function<void()>>; a basic message pump is: void message_pump( task_queue& q ) { while (auto f = q.pop()) { if (*f) (*f)(); } } you'd then make two task_queues, one for your main thread and one for your worker thread. To switch to worker instead of creating a new jthread you'd: workerq.push( [&]{ h.resume(); } ); and similarly to switch to the main mainq.push( [&]{ h.resume(); } ); there are lots of details I have skipped over, but this is a sketch of how you'd do it.
72,190,700
72,190,753
"explicit template argument list not allowed" with g++, but compiles with clang++?
I have test code as below. #include <iostream> #include <vector> using namespace std; template<typename Cont> class Test { template<typename T, typename = void> static constexpr bool check = false; template<typename T> static constexpr bool check<T, std::void_t<typename T::iterator>> = true; public: static bool fun() { return check<Cont>; } }; int main([[maybe_unused]] int argc, [[maybe_unused]] char *argv[]) { cout << Test<vector<int>>::fun() << endl; cout << Test<int>::fun() << endl; return 0; } Compile with g++, compiler will complain: test.cpp:12:27: error: explicit template argument list not allowed 12 | static constexpr bool check<T, std::void_t<typename T::iterator>> = true; | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ But the clang++ compiles the code without any error. What does the error g++ thorws mean? How can I modify the code that both g++ and clang++ compiles it? Thanks!
It should be ok to write a partial specialization in any context It is listed as a gcc bug but it is not fixed yet: gcc bug As a workaround you can place the specialization outside class context like: template<typename Cont> class Test { template<typename T, typename = void> static constexpr bool check = false; public: static bool fun() { return check<Cont>; } }; template<typename Cont> template<typename T> constexpr bool Test<Cont>::check<T, std::void_t<typename T::iterator>> = true; int main([[maybe_unused]] int argc, [[maybe_unused]] char *argv[]) { cout << Test<vector<int>>::fun() << endl; cout << Test<int>::fun() << endl; return 0; }
72,190,768
72,190,943
Error: 'else' without a previous "if' even though there is not a semicolon
I made a very simple program but even though there is not a semicolon, I still get this error. Please ignore the weird intention of this program, it's for comedy purposes. #include <iostream> #include <cstdlib> using namespace std; int main() { int john, jeff, philip, joe, dave; cout << "Hello and welcome to the blessing service" << endl; cout << "please enter your name and god will" << endl; cout << "decide if you are cursed or blessed" << endl; cout << "______________________________________" << endl; cin >> john, jeff, philip, joe, dave; if (john, jeff, philip, joe, dave) cout << "you have been cursed, you will have bad luck" << endl; cout << "for the rest of your life!" << endl; else cout << "you have been blessed, enjoy your life" << endl; cout << "and keep praying to God" << endl; system ("pause"); return 0; }
For starters in this expression statement cin >> john, jeff, philip, joe, dave; there is used the comma operator. It is equivalent to ( cin >> john ), ( jeff ), ( philip ), ( joe ), ( dave ); So all the operands after the first operand ( jeff ), ( philip ), ( joe ), ( dave ) do not produce any effect. It seems you mean cin >> john >> jeff >> philip >> joe >> dave; Again in the condition of this if statement if (john, jeff, philip, joe, dave) there is used an expression with the same comma operator. The value of the expression is the value of last operand dave contextually converted to the type bool. It is unclear what you are trying to check in this if statement. Nevertheless the following pair of statements should be enclosed in a compound statement like if (john, jeff, philip, joe, dave) { cout << "you have been cursed, you will have bad luck" << endl; cout << "for the rest of your life!" << endl; } else { cout << "you have been blessed, enjoy your life" << endl; cout << "and keep praying to God" << endl; } It seems you mean something like the following #include <iostream> #include <string> #include <cstdlib> using namespace std; int main() { string name; cout << "Hello and welcome to the blessing service" << endl; cout << "please enter your name and god will" << endl; cout << "decide if you are cursed or blessed" << endl; cout << "______________________________________" << endl; cin >> name; if (name == "john" || name == "jeff" || name == "philip" || name == "joe" || name == "dave") { cout << "you have been cursed, you will have bad luck" << endl; cout << "for the rest of your life!" << endl; } else { cout << "you have been blessed, enjoy your life" << endl; cout << "and keep praying to God" << endl; } system ("pause"); return 0; } The condition in the if statement can be changed as you like.
72,191,489
72,192,351
Serving HTML as C array from Arduino code - String size limit problem
I've been working on a HTML / websocket server on a Wiznet W5100S-EVB-Pico, programmed in the Arduino IDE. It all worked fine up until now but I'm running into, I think, a string size limit. I guess it is in the way the code handles the const char but I don't know how to do it properly. I hope someone is willing to help :) Let me explain: I convert the index.html to a index_html.h file containing a const char array: const char c_index_html[] = { 0x3c,0x21,0x44,0x4f,0x43,..., ..., 0x6d,0x6c,0x3e}; In my code I include the index_html.h file: #include "index_html.h" Now the code that actually serves the "HTML" if (web_client){ Serial.println("New client"); // an http request ends with a blank line bool currentLineIsBlank = true; while (web_client.connected()){ if (web_client.available()){ char c = web_client.read(); if (c == '\n' && currentLineIsBlank) // if you've gotten to the end of the line (received a newline { // character) and the line is blank, the http request has ended, Serial.println(F("Sending response")); // so you can send a reply String strData; strData = c_index_html; web_client.println(strData); break; } if (c == '\n') { // you're starting a new line currentLineIsBlank = true; } else if (c != '\r') { // you've gotten a character on the current line currentLineIsBlank = false; } } } This is not the prettiest code, it's smashed together from examples and now the main culprit seems to be: String strData; strData = c_index_html; web_client.println(strData); When I add extra code to the HTML and view the page source, the code is incomplete. I tested reducing the HTML to a minimum and that solves the problem. So my main question is: How do I serve the 'const char c_index_html' without use of 'String'? But also: How could I prettify the whole 'if (web_client)' serving function? Thank you very much for making it all the way through this post and if you have a suggestion I would very much appreciate it ;)
Edit: There is a bug in the ethernet library shown in this post. I don't know if it affects you; you should look at your library implementation. I'm assuming that web_client is an instance of EthernetClient from the Arduino libraries. EthernetClient::println is inherited from Print via Stream and is defined in terms of write, which is: size_t EthernetClient::write(const uint8_t *buf, size_t size) { if (_sockindex >= MAX_SOCK_NUM) return 0; // This library code is not correct: if (Ethernet.socketSend(_sockindex, buf, size)) return size; setWriteError(); return 0; } So we see that it asks the socket to send the buffer up to some size. The socket can respond with a size or 0 (see edit); if it responds with 0 then there's an error condition to check. Edit: This is how it's supposed to work. Since write is always returning the requested size and not telling you how much was written, you can't fix your problem using the print/write facilities and need to directly use socketSend. You're not checking the result of this write (which is supposed to come through println) so you don't know whether the socket sent size bytes, 0 bytes, or some number in between. In EthernetClient::connect we see that it's opening a TCP stream: _sockindex = Ethernet.socketBegin(SnMR::TCP, 0); When you call socketSend you're actually just copying your buffer into a buffer in the network stack. The TCP driver writes out that buffer when it can. If you're writing into that buffer faster than it's being flushed to the network then you'll fill it up and your socketSend calls will start returning < size bytes. See Does send() always send whole buffer?. So you're probably right that your string is too long. What you need to do is spread your writes out. There are countless tutorials covering this on the web; it's roughly like this in your example: ... size_t bytesRemaining = 0; while (web_client.connected()){ if (bytesRemaining > 0) { // Still responding to the last request char const* const cursor = c_index_html + sizeof(c_index_html) - bytesRemaining; size_t const bytesWritten = web_client.write(cursor, bytesRemaining); if (!bytesWritten) { // check for error } bytesRemaining -= bytesWritten; if (bytesRemaining == 0) { // End the message. This might not write! // We should add the '\n' to the source array so // it's included in our write-until-finished routine. web_client.println(); // Stop listening break; } } else if (web_client.available()){ // Time for a new request char c = web_client.read(); if (c == '\n' && currentLineIsBlank) { Serial.println(F("Sending response")); // Start responding to this request bytesRemaining = sizeof(c_index_html); continue; } ...
72,192,073
72,192,161
Strange C++ output with boolean pointer
I have the following code: #include <iostream> using namespace std; int main() { int n = 2; string s = "AB"; bool* xd = nullptr; for (int i = 0; i < n; i += 100) { if (xd == nullptr) { bool tmp = false; xd = &tmp; } cout << "wtf: " << " " << (*xd) << " " << endl; } } When I run this on my own mac with g++ -std=c++17, I get a random integer every time (which is odd since *xd should be a bool). Weirdly enough, this doesn't happen on online IDEs like csacademy and onlinegdb.
if (xd == nullptr) { bool tmp = false; xd = &tmp; } tmp is an automatic variable. It is destroyed automatically at the end of the scope where the variable is declared. In this case, the lifetime of the object ends when the if-statement ends. At that point, the pointer xd which pointed to the variable becomes invalid. (*xd) Here, you indirect through an invalid pointer. That's something that a program must never do. The behaviour of the program is undefined. The program is broken. Don't do this.
72,192,352
72,192,527
Template argument dependent using/typedef declaration
How can I write a using (or typedef) declaration that is dependent on a template argument? I would like to achieve something like this: template<typename T> class Class { // T can be an enum or an integral type if constexpr (std::is_enum<T>::value) { using Some_type = std::underlying_type_t<T>; } else { using Some_type = T; } };
This is exactly what std::conditional is for: template <class T> class Class { using Some_type = typename std::conditional_t<std::is_enum<T>::value, std::underlying_type<T>, std::type_identity<T>>::type; }; std::type_identity is from C++20, which if you don't have is easy to replicate yourself: template< class T > struct type_identity { using type = T; }; This is required since std::underlying_type<T>::type does not exist if T is not an enum and std::conditional can't prevent that evaluation from occurring.
72,193,031
72,193,077
No match for ‘boost::shared_ptr::operator=’
This is the code I have that causes the error below: class CAlternateMerchantList { public: CAlternateMerchant::SP m_pAlternateMerchantList[MAX_PLAYER_LIST]; int m_nMax; int m_nCur; CAlternateMerchantList() { int i; for (i = 0; i < MAX_PLAYER_LIST; i++) m_pAlternateMerchantList[i] = NULL; m_nMax = 0; m_nCur = 0; } The error I get is the following: PersonalShop.h: In constructor ‘CAlternateMerchantList::CAlternateMerchantList()’: PersonalShop.h:227: error: no match for ‘operator=’ in ‘((CAlternateMerchantList*)this)->CAlternateMerchantList::m_pAlternateMerchantList[i] = 0’ /usr/local/include/boost-1_65_1/boost/smart_ptr/shared_ptr.hpp:547: note: candidates are: boost::shared_ptr<T>& boost::shared_ptr<T>::operator=(const boost::shared_ptr<T>&) [with T = CAlternateMerchant] As you can see, I'm using boost 1_65_1 libraries. If I am not wrong, this code worked on another system with boost 1_59, but at the moment I can not access it for testing. Does anyone know how to make this code work with boost 1.65? Or, is there any other issue here?
You don't need to set boost::shared_ptrs to null. They have a default constructor which does it automatically. You can simply delete the entire for loop. I suggest also using an initialization list for m_nMax and m_nCur. CAlternateMerchantList() : m_nMax(0), m_nCur(0) { }
72,193,320
72,193,543
Why no std::as_const overload for pointer types
I just came across std::as_const and I was surprised by the output of the last line in the following snippet: #include <cstdio> #include <utility> struct S { void foo() { std::puts("foo: non const"); } void foo() const { std::puts("foo: const"); } }; int main() { S s; s.foo(); // foo: non const std::as_const(s).foo(); // foo: const auto* s_ptr = &s; s_ptr->foo(); // foo: non const std::as_const(s_ptr)->foo(); // foo: non const (?) } Looking at the documentation, I understand why the non-const overload of foo gets called: std::as_const(s_ptr) returns a S* const&, i.e. a reference to a constant pointer to non constant S, instead of a S const*, i.e. a pointer to a constant S, as I would have expected. So, my question is why doesn't the standard provide a std::as_const overload for pointer types too? E.g. something like: template <class T> constexpr std::add_const_t<T>* as_const(T* t) noexcept { return t; } Edit: one of the motivations for std::as_const in paper P0007R1 is the selection of a function oveload without having to resort to a const_cast. P0007R1 provides this example: int processEmployees( std::vector< Employee > &employeeList ); bool processEmployees( const std::vector< Employee > &employeeList ); A larger project often needs to call functions, like processEmployees, and selecting among specific const or non-const overloads. [...] That's why I was somehow surprised it doesn't help in overload resolution when applied to a pointer in code like the one I posted, nor in: std::as_const(this)->foo(); nor in selecting the latter of the following overloads: int processEmployees( std::vector< Employee > *employeeList ); bool processEmployees( const std::vector< Employee > *employeeList );
The purpose of std::as_const is to be able to reference a non-const lvalue as a const lvalue so that it isn't modifiable in the context in which it is used. In other words std::as_const(x) should be a shorthand for writing const auto& y = x; and then using y. It already does that well, so there is no need for special behavior for pointers. And here is a simple example where the suggested additional overload would have serious negative effects: std::vector<int> vec = /*...*/; for(auto it = std::begin(vec); it != std::end(vec); it++) func(std::as_const(it)); The intention here is to make sure that the function func cannot modify it since the responsibility of iterating over the vector lies with the for loop. If func simply takes an iterator by-value or const reference, then std::as_const is not strictly required, but it makes sense anyway as a safety measure or because there are multiple overloads of func, some of which do modify their argument. auto here is some iterator type. It could be a pointer. Or it could be a class type. With your suggested overload of as_const this would break depending on how the std::vector iterator is implemented. std::as_const(it) is supposed to say that it shall not be modified through this use. It shouldn't say anything about whether the object it references is modifiable. That is not its purpose. Of course it could make sense to add a function that makes the referenced object non-modifiable. But that should have a different name and you would probably want to implement it for arbitrary iterators, not pointers specifically. Basically, an iterator-to-const-iterator adaptor.
72,193,329
72,193,561
Why are integer return values (such as -1 or 0) used in C and C++?
When I read C or C++ code, I often notice that functions return integer values such as -1 or 0. My question is: why are these integer return values used? It appears that -1 is returned by functions when they are unable to do what they were intended to do. So are these values like HTTP response status codes? If so, how many other values exist and what do they represent?
I assume that you refer to the return value of main. This is what the C++ standard says about it: [basic.start.main] A return statement ([stmt.return]) in main has the effect of leaving the main function (destroying any objects with automatic storage duration) and calling std​::​exit with the return value as the argument. [support.start.term] [[noreturn]] void exit(int status); Effects: ... Finally, control is returned to the host environment. If status is zero or EXIT_­SUCCESS, an implementation-defined form of the status successful termination is returned. If status is EXIT_­FAILURE, an implementation-defined form of the status unsuccessful termination is returned. Otherwise the status returned is implementation-defined. So, the meaning of the return value is largely implementation-defined. Many operating system (such as Linux, Windows, Mac, etc.) shells have a concept of "exit status code". Typically, implementations of C++ forward the returned value as the exit status code. The meaning of such status may depend on the environment where the program runs. For example, this is what the manual of bash (which is a shell for Linux) says: ... Exit statuses fall between 0 and 255, though, as explained below, the shell may use values above 125 specially. ... For the shell’s purposes, a command which exits with a zero exit status has succeeded. A non-zero exit status indicates failure.
72,193,426
72,216,043
Native WebRTC crashes in webrtc::PeerConnectionInterface::RTCConfiguration destructor
I'm writing a WebRTC client in C++. It needs to work cross platform. I'm starting with a POC on Windows. I can connect and disconnect to/from the example peerconnection_server.exe. Per the Microsoft "getting started" tutorial (https://learn.microsoft.com/en-us/winrtc/getting-started), I'm using the WebRTC "M84" release. I'm aware of this similar SO post, but it is not the same issue, so please don't point me to that: WebRTC crash at line webrtc::PeerConnectionInterface::RTCConfiguration config; for Native Linux application That's a constructor matter on Linux. My problem is the destructor on Windows... (clearly that class must have flaws in general..) Getting to the point, I've found that I can't ever destroy a webrtc::PeerConnectionInterface::RTCConfiguration object. If I do, a fatal error is produced saying something about the app writing to the heap in some illegal manner. It makes no difference how or when I use that class - it always blows up on destruction. All one needs to do test this is the following: webrtc::PeerConnectionInterface::RTCConfiguration *config = new webrtc::PeerConnectionInterface::RTCConfiguration(); delete config; On the delete line - kaboom! I've found assorted examples of this config class being used. No one looks to have any such issues, and don't appear to be jumping through hoops to deal with this. Typically, one of those objects is created when a PeerConnection is, and then just allowed to scope out of a local function. Considering it's a "config" object, it ought to be rather benign - but apparently not! What secret trick is involved here? Looking at the source, the definition of the default constructor & destructors are maximally trivial. So, is the bug in some member object in the config? PeerConnectionInterface::RTCConfiguration::RTCConfiguration() = default; ... PeerConnectionInterface::RTCConfiguration::~RTCConfiguration() = default;
Turns out this is specific to not only Windows/MSVC, but to DEBUG mode. In release mode, this doesn't happen for me. Apparently, it's caused by some linkage mismatch. If you compile with a given /MDd or /MT switch, etc. you'll run into such issues if you link to other libs or dlls which don't agree on that detail. (It's notable, however, that I have yet to see any other such problems in my build - only this one destructor is misbehaving. Weird!) Getting WebRTC to build in Windows requires assorted linkage to Windows SDK and system libraries. At least one of them must be mismatched for me. So, here's the workaround - just automatically ignore the errors! First, for convenience, set a #define to identify to the conditional scenario. I'm using Qt, so that looks like this for me: #if defined(QT_DEBUG) && defined(Q_CC_MSVC) #define MSVC_DEBUG #endif Then, include this Windows api header: #ifdef MSVC_DEBUG #include <crtdbg.h> #endif I'm managing my config object via an std::unique_ptr (using STL rather than Qt in this .cpp since WebRTC doesn't use Qt of course, and it's cleaner to use a "When in Rome..." approach): std::unique_ptr<webrtc::PeerConnectionInterface::RTCConfiguration> connConfig_; Finally, when I want to destroy this object, I call a function resembling the following: // Note: in Windows debug mode this destructor produces a heap assertion // failure, which would create an ugly popup if not for the explicit // suppression code surrounding the reset() below void SomeClass::destroyConnectionConfig() { if( !connConfig_.get() ) return; #ifdef MSVC_DEBUG // Temporarily disabled popup error messages on Windows auto warnCrtMode( _CrtSetReportMode( _CRT_WARN, _CRTDBG_MODE_FILE ) ); auto warnCrtFile( _CrtSetReportFile( _CRT_WARN, _CRTDBG_FILE_STDERR ) ); auto errorCrtMode( _CrtSetReportMode( _CRT_ERROR, _CRTDBG_MODE_FILE ) ); auto errorCrtFile( _CrtSetReportFile( _CRT_ERROR, _CRTDBG_FILE_STDERR ) ); auto assertCrtMode( _CrtSetReportMode( _CRT_ASSERT, _CRTDBG_MODE_FILE ) ); auto assertCrtFile( _CrtSetReportFile( _CRT_ASSERT, _CRTDBG_FILE_STDERR ) ); auto errorMode( _set_error_mode( _OUT_TO_STDERR ) ); #endif connConfig_.reset(); #ifdef MSVC_DEBUG // Restore error handling setttings _CrtSetReportMode( _CRT_WARN, warnCrtMode ); _CrtSetReportFile( _CRT_WARN, warnCrtFile ); _CrtSetReportMode( _CRT_ERROR, errorCrtMode ); _CrtSetReportFile( _CRT_ERROR, errorCrtFile ); _CrtSetReportMode( _CRT_ASSERT, assertCrtMode ); _CrtSetReportFile( _CRT_ASSERT, assertCrtFile ); _set_error_mode( errorMode ); #endif }
72,193,730
72,235,510
Generating a call graph with clang's -dot-callgraph with multiple cpp files, and a sed command
I tried Doxygen, but it was a bit slow, and it generated a lot of irrelevant individual dot files, so I'm pursuing the clang way to generate a call graph. This answer https://stackoverflow.com/a/5373814/414063 posted this command: $ clang++ -S -emit-llvm main1.cpp -o - | opt -analyze -dot-callgraph $ dot -Tpng -ocallgraph.png callgraph.dot and then $ clang++ -S -emit-llvm main1.cpp -o - | opt -analyze -std-link-opts -dot-callgraph $ cat callgraph.dot | c++filt | sed 's,>,\\>,g; s,-\\>,->,g; s,<,\\<,g' | gawk '/external node/{id=$1} $1 != id' | dot -Tpng -ocallgraph.png I managed to get the .dot files and unmangle them with c++filt, but the symbols are made of a lot of "noise", example: "{__gnu_cxx::new_allocator<std::_Rb_tree_node<std::pair<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > > > >::deallocate(std::_Rb_tree_node<std::pair<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > > >*, unsigned long)}" "{void std::allocator_traits<std::allocator<std::_Rb_tree_node<std::pair<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > > > > >::destroy<std::pair<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > > >(std::allocator<std::_Rb_tree_node<std::pair<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > > > >&, std::pair<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > >*)}" "{void __gnu_cxx::new_allocator<std::_Rb_tree_node<std::pair<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > > > >::destroy<std::pair<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > > >(std::pair<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > >*)}" How does doxygen manage to "simplify" those symbols? Is there anything else other than STLfilt? How can I properly filter symbols that are not relevant to my code, like allocators, constructors for containers? What does this sed and gawk command attempt to do? I tried them but I could not really see what they did.
I managed to do it, but it was not really trivial, and clang doesn't really provide options to filter "noisy" symbols. It is important to know that graphviz cannot magically optimize the layout of a graph, so it's better to generate one graph per object file. Here is the python filter I came up with to remove a lot of the noise. There are various things that are not part of std::, like sfml or nlohmann (a heavy templated json library that will generate a lot of symbols). I did not use regex, as it was not really relevant. Those filters should vary a lot depending on your code, the library you use, and eventually what parts of the standard library you use, since "it's just templates all the way down". def filtered(s): return not ( s.startswith("& std::__get_helper") or s.startswith("__cx") or s.startswith("__gnu_cxx::") or s.startswith("bool nlohmann::") or s.startswith("bool std::") or s.startswith("decltype") or s.startswith("int* std::") or s.startswith("int** std::") or s.startswith("nlohmann::") or s.startswith("sf::") or s.startswith("std::") or s.startswith("void __gnu_cxx::") or s.startswith("void format<") or s.startswith("void nlohmann::") or s.startswith("void std::") or 'std::remove_reference' in s or 'nlohmann::' in s or '__gnu_cxx::' in s or 'std::__copy_move' in s or 'std::__niter' in s or 'std::__miter' in s or 'std::__get_helper' in s or 'std::__uninitialized' in s or 'sf::operator' in s or s == 'sf::Vector2<float>::Vector2()' or s == 'sf::Vector2<float>::Vector2(float, float)' or s == 'sf::Vector2<float>::Vector2<int>(sf::Vector2<int> const&)' or s == 'sf::Vector2<int>::Vector2()' or s == 'sf::Vector2<int>::Vector2(int, int)' ) Second, I also removed symbols that were not called, and calls to node absent from the object file. Concretely, I just cross checked nodes and edges in the generated DOT file # filtering symbols I don't want nodes_filtered = [(name, label) for (name, label) in nodes if filtered(label)] # using a set() for further cross checking nodes_filt_ids = set([name for (name, label) in nodes_filtered]) # we only keep edges with symbols (source and destination) BOTH present in the list of nodes edge_filtered = [(a,b) for (a,b) in edges if a in nodes_filt_ids and b in nodes_filt_ids] # we then build a set() of all the nodes from the list of edges nodes_from_filtered_edges = set(sum(edge_filtered, ())) # we then REFILTER AGAIN from the list of filtered edges nodes_refiltered = [(name, label) for (name, label) in nodes_filtered if name in nodes_from_filtered_edges] Third, I used a makefile to cascade steps. object_file.ll: object_file.cpp 2dhelpers.h.gch $(CC) -S -emit-llvm $< -o $@ $(args) $(inclflags) object_file.ll.callgraph.dot: object_file.ll opt $< -std-link-opts -dot-callgraph object_file.cxxfilt.dot: object_file.ll.callgraph.dot cat $< | llvm-cxxfilt > $@ object_file.cleaned.dot: object_file.cxxfilt.dot python3 dot-parse.py $^ object_file.final.svg: object_file.cleaned.dot dot -Tsvg $^ -o $@ Important to note that llvm-cxxfilt unmangled symbols a bit better than c++filt, although it was not perfect in my case. The DOT file written by opt is quite trivial to parse, but you can still use pydot, although I found it to be a little slow, which it will if you have a lot of symbols (I have 2500 symbols, 5000 calls, reduce to 116 and 151) If you really want to "combine" multiple object files and use a single graph, you absolutely can, using llvm-link # linking llvm IR with this magic all_objects.ll: file1.ll file2.ll file3.ll file4.ll file5.ll llvm-link -S $^ -o all_objects.ll Just apply command #2 to #5 to the resulting .ll file In my case the single big graph was not easy to read, as multiple edges would cross and form "rivers". Adding color did not help a lot.
72,193,865
72,193,922
boolean function returning false even though condition is satisfied to return true in c++. Why?
My function is a simple palindrome algorithm that is supposed to take an input integer (test), turn it into a string (test_s), then reverse that string in a new variable (test_s_reverse) then return true if test_s is equal to test_s_reverse. bool is_palindrome(int test){ test_s = to_string(test); test_length = test_s.length(); for (int i=(test_length + 1); i>=0; i--){ test_s_reverse += test_s[i]; } if (test_s_reverse == test_s){ return true; } else { return false; } } I created a main function to test results and using input 12321 the program returns false, even though cout for test_s_reverse is = 12321 and test_s = 12321. What am I doing wrong?
You should use test_length - 1 instead of test_lenght + 1, because in the new reversed string you have some extra characters which you can't see if you print them. The .length() function returns you exactly the number of characters in the string. So you either go with test_length, but you do i>0, or if you go in the loop with i>=0 you go with test_length - 1, so you will be sure that there are no blank characters at the end of new string. But, if you start with test_length, you will need to edit, since there is no character at test_length position: test_s_reverse += test_s[i-1]; If you use pure C++ code, it should look like this: bool is_palindrome(int test){ string test_s = to_string(test); int test_length = test_s.length(); string test_s_reverse; for (int i=(test_length); i>0; i--){ test_s_reverse += test_s[i-1]; } if (test_s_reverse == test_s){ return true; } else { return false; } }
72,194,076
72,194,243
Pointer-Interconvertible Types and Arrays of Unions
If I have a union. struct None {}; template<typename T> union Storage { /* Ctors and Methods */ T obj; None none; }; pointer-interconvertible types means it is legal to perform the following conversion: Storage<T> value(/* ctor args */); T* obj = static_cast<T*>(static_cast<void*>(&value)); It is legal to treat an array of Storage<T> as an array of T? Storage<T> values[20] = { /* initialisation */ }; T* objs = static_cast<T*>(static_cast<void*>(values)); for(auto i = 0; i < 20; ++i) { objs[i].method(); // Is this pointer access legal? }
No, it is not legal. The only thing that may be treated as an array with regards to pointer-arithmetic is an array (and the hypothetical single-element array formed by an object that is not element of an array). So the "array" relevant to the pointer arithmetic in objs[i] here is the hypothetical single-element array formed by obj of the first array element, since it is not itself element of an array. For i >= 1, objs[i] will not point to an object and so method may not be called on it. Practically, there will be an issue in particular if T's size and the size of the union don't coincide, since even the arithmetic on the addresses will be off in this case. There is no guarantee that the two sizes coincide (even if None has sizeof and alignof equal to 1). Aside from that issue, I doubt that compilers actually make use of this undefined behavior for optimization purposes. I can't guarantee it though. Also note that you are only allowed to access obj through the pointer obtained by the cast if obj is the active member of the union, meaning that obj is the member which was initialized in the example. You indicate that you intend to use this in a constant expression, in which case the compiler is required to diagnose the undefined behavior and is likely to reject such a program, regardless of the practical considerations about the optimizer. Also, in a constant expression a cast from void* to a different object type (or a reinterpret_cast) is not allowed. So static_cast<T*>(static_cast<void*>(values)); will cause that to fail anyway. Although that is simply remedied by just taking a pointer to the union member directly (e.g. &values[0].obj). There is no reason to use the casts here.
72,194,964
72,250,620
Spurious wakeup with atomics and condition_variables
std::atomic<T> and std::condition_variable both have member wait and notify_one functions. In some applications, programmers may have a choice between using either for synchronization purposes. One goal with these wait functions is that they should coordinate with the operating system to minimize spurious wakeups. That is, the operating system should avoid waking the wait-ing thread until notify_one or notify_all are called. On my machine, sizeof(std::atomic<T>) is sizeof(T) and sizeof(std::condition_variable) is 72. If you exclude std::atomic<T>'s T member, then std::condition_variable reserves 72 bytes for to serve its synchronization purposes while sizeof(std::atomic<T>) reserves 0 bytes. My question: should I expect different behavior between std::condition_variable's and std::atomic<T>'s wait functions? For example, should std::condition_variable have fewer spurious wakeups? std::atomic<T>::wait() std::atomic<T>::notify_one() std::condition_variable::wait() std::condition_variable::notify_one()
My question: should I expect different behavior between std::condition_variable's and std::atomic<T>'s wait functions? For example, should std::condition_variable have fewer spurious wakeups? std::atomic::wait does not have spurious wake ups. The standard guarantees that a changed value was observed, it says in [atomics.types.generic.general]/30: Effects: Repeatedly performs the following steps, in order: (30.1) Evaluates load(order) and compares its value representation for equality against that of old. (30.2) If they compare unequal, returns. (30.3) Blocks until it is unblocked by an atomic notifying operation or is unblocked spuriously. So, if the underlying implementation of atomic wait makes spurious wake ups, they are hidden by the C++ standard library implementation. If your questions is about whether there are more or fewer spurious wakeups in the underlying implementation of atomics or condition variables, then it is implementation specific. Will depend on operating system and library implementation. Most likely answer is: no, because the ultimate implementation, where OS makes kernel call is highly likely the same.
72,195,181
72,195,348
Using Templates to set function types in a class gives error
So I have this class: template <typename callBackOne, typename callBackTwo> class MyClass { // The class public: callBackOne cbo; callBackTwo cbt; MyClass(callBackOne cbop, callBackTwo cbtp){ cbop(); cbtp(); } }; All it does is call the functions you give in the parameter for its constructor. The callback function types are deduced by a template. I cannot do this any other way. Why does it error when I try: MyClass<void,void> test(voidFuncOne,voidFuncTwo); The error: error: invalid parameter type ‘void’ no matching function for call to ‘MyClass<void, void>::MyClass(int (&)(), void (&)())’ 24 | MyClass<void,void> testy(test,testTwo); Ive tried lots of different things including: MyClass<void(&)(),void(&)()> test(test,testTwo); MyClass<void,void> test(&test,&testTwo); MyClass<void (*)(void),void (*)(void)> test(test,testTwo); I know its possible to pass in functions as parameters like this but i just cant figure out how. Its a problem of knowledge of the language.
The problem is that the explicit template arguments that you're passing are of type void but the function arguments voidFuncOne and voidFuncTwo will be implicitly converted to void (*)() and passed but since there is no conversion from a void(*)() to void you get the mentioned error. C++17 With C++17, you can make use of class template argument deduction(aka CTAD) as shown below: template <typename callBackOne, typename callBackTwo> class MyClass { // The class public: callBackOne cbo; callBackTwo cbt; MyClass(callBackOne cbop, callBackTwo cbtp){ cbop(); cbtp(); } }; void voidFuncOne() { std::cout<<"funcone called"<<std::endl; } void voidFuncTwo() { std::cout<<"functow called"<<std::endl; } MyClass test(voidFuncOne,voidFuncTwo); //CTAD used automatically here //-----^------------------------------->no need to pass arguments explicitly since CTAD will be used Demo Pre-C++17 Here you can explicitly specify the template arguments to be of type void(*)() as shown below: template <typename callBackOne, typename callBackTwo> class MyClass { // The class public: callBackOne cbo; callBackTwo cbt; MyClass(callBackOne cbop, callBackTwo cbtp){ cbop(); cbtp(); } }; void voidFuncOne() { std::cout<<"funcone called"<<std::endl; } void voidFuncTwo() { std::cout<<"functow called"<<std::endl; } //------vvvvvvvvv--vvvvvvvvv--------------------------------->template arguments changed from void to void(*)() MyClass<void(*)(), void(*)()> test(voidFuncOne,voidFuncTwo); Demo
72,195,327
72,195,437
indexing an element from a volatile struct doesn't work in C++
I have this code: typedef struct { int test; } SensorData_t; volatile SensorData_t sensorData[10]; SensorData_t getNextSensorData(int i) { SensorData_t data = sensorData[i]; return data; } int main(int argc, char** argv) { } It compiles with gcc version 8.3, but not with g++. Error message: main.c: In function ‘SensorData_t getNextSensorData(int)’: main.c:8:34: error: no matching function for call to ‘SensorData_t(volatile SensorData_t&)’ SensorData_t data = sensorData[i]; ^ main.c:3:3: note: candidate: ‘constexpr SensorData_t::SensorData_t(const SensorData_t&)’ <near match> } SensorData_t; ^~~~~~~~~~~~ main.c:3:3: note: conversion of argument 1 would be ill-formed: main.c:8:34: error: binding reference of type ‘const SensorData_t&’ to ‘volatile SensorData_t’ discards qualifiers SensorData_t data = sensorData[i]; ~~~~~~~~~~~~^ main.c:3:3: note: candidate: ‘constexpr SensorData_t::SensorData_t(SensorData_t&&)’ <near match> } SensorData_t; ^~~~~~~~~~~~ main.c:3:3: note: conversion of argument 1 would be ill-formed: main.c:8:34: error: cannot bind rvalue reference of type ‘SensorData_t&&’ to lvalue of type ‘volatile SensorData_t’ SensorData_t data = sensorData[i]; I'm not sure if I need to add volatile as well for the data variable and the return type, shouldn't be needed because it is copied. But I do access the sensorData array from an interrupt as well (on an embedded system), so I think I need volatile for the top level variable sensorData.
Your program is trying to copy a SensorData_t object. The compiler supplies a copy constructor with the following signature: SensorData_t(const SensorData_t &) This copy constructor will not work with volatile arguments, hence the compilation error. You can write your own copy constructor which works with volatile SensorData_t objects (as well as non-volatile SensorData_t objects): struct SensorData_t { SensorData_t() = default; SensorData_t(const volatile SensorData_t &other) : test(other.test) { } int test; };
72,195,354
72,195,484
I had try to run a car game through c++ only
As mentioned in the title I try to run a car game developed using only CPP but faced problems in line 20 of my code... #include<conio.h> #include<dos.h> #include <windows.h> #include <time.h> #define SCREEN_WIDTH 90 #define SCREEN_HEIGHT 26 #define WIN_WIDTH 70 using namespace std; HANDLE console = GetStdHandle(STD_OUTPUT_HANDLE); COORD CursorPosition; int enemyY[3]; int enemyX[3]; int enemyFlag[3]; char car[1][1] = {{' ',' '}, {'*','*','*'}};//<--------------------here int carPos = WIN_WIDTH/2; int score = 0; void gotoxy(int x, int y){ CursorPosition.X = x; CursorPosition.Y = y; SetConsoleCursorPosition(console, CursorPosition); } void setcursor(bool visible, DWORD size) { if(size == 0) size = 20; CONSOLE_CURSOR_INFO lpCursor; lpCursor.bVisible = visible; lpCursor.dwSize = size; SetConsoleCursorInfo(console,&lpCursor); } in my code error is poping as <> will anybody help me to find an error in my code?
You're defining your 'car' array as a 2d (1x1) array, which would need to be initialized like: char car[1][1] = {{' '}}; // probably not useful (it only holds 1 char) You probably need to change the size of your array. Something like: char car[2][3] = { // here car is 2x3, an array of size 2 { ' ', ' ', ' ' }, // each element is an array of size 3 { '*', '*', '*' } } In the future, it will be helpful if you also post the error that you're getting.
72,196,298
72,197,081
C++ startup once, listen node input design issue
I’ve build a cpp program that performs the following workflow sequentially: Read serialized data (0.3 ms) Receive search metadata (0.00.. ms) Search data (0.01 ms) Return search data(0.00.. ms) Right now, I run the program with nodejs shell exec and serve it with an express api. The api is not used by many users, so reading the data will be performed just once a while. But one user will do like 20 queries on the same data. So right now, reading is performed 20 times on the same data. Obviously reading the data takes most of the time. Additionally, the data that is being read never changes. To speed up the workflow, I want to read the data once, then wait for requests. Just like a MySQL db, that is waiting for statements. What would be your approach to do that? Should I build a socket server? (Feels overkill) Should I try to run the Programm in background, store the pid and use a nodejs shell exec solution? (Feels hacky) I think I’m missing the right terms. And it would be awesome if you can push me in the right direction!
You may call C++ directly from nodejs which should save you from overhead either executing the shell or building the socket server. Eg: int Feed(const char* searchMetadata) which returns a key of data if you want multiple metadata being saved in C++part. Then call const char* search(int dataKey, const char* searchingKeyword) to search the meta data. Then call search() as many times as you need. It's also doable to cache the data as a file for C++. However you consider 0.3ms is an overhead, then it's better to avoid file open/save.
72,197,030
72,197,264
How to pass a template function to another function and apply it
// I can't change this function! template<typename Function, typename... Args> void RpcWriteKafka(Function func, Args&&... args) { func(std::forward<Args>(args)...); } // I can change this one if necessary. template<typename FUNC, typename... Args, typename CALLBACK, typename... CArgs> void doJob(std::tuple<CALLBACK, CArgs&&...> tp, FUNC func, Args&&... args) { // SetValues(std::forward<Args>(args)...); std::apply(func, tp); } int main() { doJob(std::make_tuple([](int i){}, 1), RpcWriteKafka, 1); return 0; } As you see, some library provided the template function RpcWriteKafka. It needs the parameter about a callback function(func) and its parameters(args...). I want to define my own function doJob, which allows me to call it like this: doJob(std::make_tuple([](int i){}, 1), RpcWriteKafka, 1);. I'm expecting that the first parameter, which is a std::tuple, could be passed to the second parameter RpcWriteKafka. Why do I used std::tuple: How to pass a function with parameter pack to a function with parameter pack For now, it can't be compiled. The compiler generated two errors: mismatched types 'CArgs&&' and 'int', which comes from the 1 in that tuple; the second parameter RpcWriteKafka is unresolved overloaded function type. So how to solve the two issues? Is it possible to define such a function doJob so that I can call it easily as shown in the main above?
First, the first parameter type of doJob should be std::tuple<CALLBACK, CArgs...> instead of std::tuple<CALLBACK, CArgs&&...> since CArgs&& cannot be deduced in such context. Second, since RpcWriteKafka is a function template, you can't pass it to doJob like this, instead, you need to wrap it with lambda, so this should work (I omit the Args&&... because it is not used) template<typename CALLBACK, typename... CArgs, typename FUNC> void doJob(std::tuple<CALLBACK, CArgs...>&& tp, FUNC func) { std::apply(func, tp); } int main() { doJob(std::make_tuple([](int i){}, 1), [](auto... args) { RpcWriteKafka(args...); }); }
72,197,093
72,197,700
What is the need for having two different syntaxes for specializing data member of a class template
I was writing an example involving specialization of class template where I noticed that the standard allows two different syntax for specialization of a data member as shown below: template<typename T > struct C { static int x; }; template<> struct C<bool> { static int x; }; //here we cannot write prefix template<> int C<bool>::x = 0; As can be seen in the above example, we are not allowed to write the prefix template<> for defining the static data member x. And i understand this and have no problem with the above example. But when i modified the example to look like as shown below, i was surprised to see that we are allowed/required to write the prefix template for defining the static data member x: template<typename T > struct C { static int x; }; template<> //here why is the use of prefix template<> allowed/required? Why standard mandates that we cannot omit this prefix template<> here but in the previous example we can omit it int C<bool>::x = 0; As can be seen in the above modified example, we are required to use the prefix template<> for defining the same static data member x. My question is that why is there a difference in syntax for defining the same data member x in the above two examples. That is why the standard requires the use of prefix template<> in the second example. Why can't we omit that prefix in the second example just like first example. Does using the prefix template<> in the second example help solve some problem(like some ambiguity or something else). PS: Note that my question is not about which statement from the standard allows this usage(since i already know using the below given quoted statement from cppreference) but about the rationale for allowing these two syntaxes(one that uses template<> and one that doesn't). I also came across the following and the code example given in the mentioned link that explain how this is allowed: When defining a member of an explicitly specialized class template outside the body of the class, the syntax template<> is not used, except if it's a member of an explicitly specialized member class template, which is specialized as a class template, because otherwise, the syntax would require such definition to begin with template required by the nested template . The above quoted statement explains along with the example given there explains how the standard allows the above given examples in my question. But i am looking for a reason why is the prefix template<> mandated by the standard in the second example. Why standard doesn't allow the ommision of prefix template<> in the second example as in example 1.
Explicit specialization declaration of a class template is not a template declaration. [Source]. This means that when we provide an explicit specialization for a class template, it behaves like an ordinary class. Now we can apply this to the examples given in question. Example 1 template<typename T > struct C { static int x; }; //this is an specialization and so we must use template<> prefix template<> struct C<bool> { static int x; }; //this is just ordinary out of class definition of data member `x`. That is, this is not a specialization and so we don't need the prefix template<> int C<bool>::x = 0; In the above example, first we have provided an explicit specialization for bool of the class template C itself which behaves like an ordinary class(in the sense that it is not a template declaration). The template<> prefix is needed here because we were providing a specialization. Next, we provide an ordinary out-of-class definition of the static data member x of the specialization that we provided. But here we don't need the template<> prefix because this is not a specialization. This is just an ordinary out-of-class definition of a static data member. Example 2 template<typename T > struct C { static int x; }; template<> // needed because this is not an ordinary out-of-class definition of data member x. Instead this is a specialization int C<bool>::x = 0; In the above example, we have not provided any explicit specialization for class template C. Instead we are directly providing a specialization for the static data member x. This means that unlike example 1, here we are not providing an out-of-class definition of a static data member but instead we're providing a specialization. So in this case we need the template<> prefix. TLDR In example 1 int C<bool>::x = 0; is just an ordinary out-of-class definition of a static data member x and not a specialization, so we don't need the prefix template<> for this. Conversely, in example 2 template<> int C<bool>::x = 0; is a specialization of a static data member x and not an ordinary out-of-class definition. So in this case(example 2) the prefix template<> is needed.
72,197,242
72,197,410
What is wrong with my application of SFINAE when trying to implement a type trait?
I needed a type trait that decays enums to their underlying type, and works the same as decay_t for all other types. I've written the following code, and apparently this is not how SFINAE works. But it is how I thought it should work, so what exactly is the problem with this code and what's the gap in my understanding of C++? namespace detail { template <typename T, std::enable_if_t<!std::is_enum_v<T>>* = nullptr> struct BaseType { using Type = std::decay_t<T>; }; template <typename T, std::enable_if_t<std::is_enum_v<T>>* = nullptr> struct BaseType { using Type = std::underlying_type_t<T>; }; } template <class T> using base_type_t = typename detail::BaseType<T>::Type; The error in MSVC is completely unintelligible: 'detail::BaseType': template parameter '__formal' is incompatible with the declaration In GCC it's a bit better - says that declarations of the second template parameter are incompatible between the two BaseType templates. But according to my understanding of SFINAE, only one should be visible at all for any given T and the other one should be malformed thanks to enable_if. Godbolt link
SFINAE applied to class templates is primarily about choosing between partial specialisations of the template. The problem in your snippet is that there are no partial specialisations in sight. You define two primary class templates, with the same template name. That's a redefinition error. To make it work, we should restructure the relationship between the trait implementations in such as way that they specialise the same template. namespace detail { template <typename T, typename = void> // Non specialised case struct BaseType { using Type = std::decay_t<T>; }; template <typename T> struct BaseType<T, std::enable_if_t<std::is_enum_v<T>>> { using Type = std::underlying_type_t<T>; }; } template <class T> using base_type_t = typename detail::BaseType<T>::Type; The specialisation provides a void type for the second argument (just like the primary would be instantiated with). But because it does so in a "special way", partial ordering considers it more specialised. When substitution fails (we don't pass an enum), the primary becomes the fallback. You can provide as many such specialisation as you want, so long as the second template argument is always void, and all specialisations have mutually exclusive conditions.
72,197,420
72,199,804
std::time() and its dependence on daylight saving
I have a requirement to lock a user, if 3 consecutive login attempts are failed within 15 minutes. I am going to check with the following formula, if third login attempt fails. if (first_login_attemp_time + 900 <= std::time(nullptr)) { lockuser(); } If the first login attempt fails, I set first_login_attemp_time as given below first_login_attemp_time = std::time(nullptr) Will this code work if daylight saving time change occurs in the 15 minutes window? Should I consider something else for day light saving?
The std::time returns UTC time that does not follow daylight saving policies of local authorities. So about daylight savings there are no worries. Like the cited reference article says most systems implement std::time_t (that std::time returns) as in POSIX standard. In my experience it is all systems that I know of. So it is extremely likely to be integral value in seconds and so your + 900 results with its advance by 15 minutes. However logic of your code is strange. It locks user when more than 15 minutes has passed since first attempt and that is not usually what is called "within 15 minutes".
72,197,597
72,197,782
c++ constexpr concatenate char*
Context: In my company we generate a lot of types based on IDL files. Some of the types require special logic so they are handcoded but follow the same pattern as the generated ones. We have a function which all types must implement which is a name function. This will return the type name as a char* string and the function is constexpr. Problem: The problem is regarding collections which could contain other collections nested potentially N number of times. I therefore am trying to concatenate two or more char* strings at compile time. Pseudocode of what I want to achieve: template <typename T> constexpr char* name() { constexpr char* collectionName = "std::vector"; constexpr char* containedTypeName = name<T>(); return concat(collectionName, "<", containedTypeName, ">"); } Note: There are examples out there which does something like this but is done with char[] or the use of static variables. The question: How can I make a constexpr function which return a char* which consists of two or more concatenated char* strings at compile time? I am bound to C++17.
From constexpr you cannot return char* which is constructed there... You must return some compile time known(also its size) constant thingy. A possible solution could be something like: #include <cstring> // Buffer to hold the result struct NameBuffer { // Hardcoded 128 bytes!!!!! Carefully choose the size! char data[128]; }; // Copy src to dest, and return the number of copied characters // You have to implement it since std::strcpy is not constexpr, no big deal. constexpr int constexpr_strcpy(char* dest, const char* src); //note: in c++20 make it consteval not constexpr template <typename T> constexpr NameBuffer name() { // We will return this NameBuffer buf{}; constexpr const char* collectionName = "std::vector"; constexpr const char* containedTypeName = "dummy"; // Copy them one by one after each other int n = constexpr_strcpy(buf.data, collectionName); n += constexpr_strcpy(buf.data + n, "<"); n += constexpr_strcpy(buf.data + n, containedTypeName); n += constexpr_strcpy(buf.data + n, ">"); // Null terminate the buffer, or you can store the size there or whatever you want buf.data[n] = '\0'; return buf; } Demo And since the returned char* is only depends on the template parameter in your case, you can create templated variables, and create a char* to them, and it can act like any other char*... EDIT: I have just realized that your pseudo code will never work!! Inside name<T>() you are trying to call name<T>(). You must redesign this!!! But! With some hack you can determine the size at compile time somehow for example like this: #include <cstring> #include <iostream> template<std::size_t S> struct NameBuffer { char data[S]; }; // Copy src to dest, and return the number of copied characters constexpr int constexpr_strcpy(char* dest, const char* src) { int n = 0; while((*(dest++) = *(src++))){ n++; } return n; } // Returns the len of str without the null term constexpr int constexpr_strlen(const char* str) { int n = 0; while(*str) { str++; n++; } return n; } // This template parameter does nothing now... // I left it there so you can see how to create the template variable stuff... //note: in c++20 make it consteval not constexpr template <typename T> constexpr auto createName() { constexpr const char* collectionName = "std::vector"; constexpr const char* containedTypeName = "dummy"; constexpr std::size_t buff_size = constexpr_strlen(collectionName) + constexpr_strlen(containedTypeName) + 2; // +1 for <, +1 for > /// +1 for the nullterm NameBuffer<buff_size + 1> buf{}; /// I'm lazy to rewrite, but now we already calculated the lengths... int n = constexpr_strcpy(buf.data, collectionName); n += constexpr_strcpy(buf.data + n, "<"); n += constexpr_strcpy(buf.data + n, containedTypeName); n += constexpr_strcpy(buf.data + n, ">"); buf.data[n] = '\0'; return buf; } // Create the buffer for T template<typename T> static constexpr auto name_buff_ = createName<T>(); // point to the buffer of type T. It can be a function too as you wish template<typename T> static constexpr const char* name = name_buff_<T>.data; int main() { // int is redundant now, but this is how you could use this std::cout << name<int> << '\n'; return 0; } Demo
72,197,716
72,197,825
Why the std::is_array in template function is not distinguishing between int and array type?
In the following code, I am using a template function and type traits to distinguish between an integer type (else case) and array type. I would expect the output to be int and array respectively, instead I get int int with the two calls that instantiates the template functions respectively with an int type and an array type: Why is that? #include <iostream> #include <array> template <typename T> inline static void constexpr SetCoordinates() { if (std::is_array<T>::value) std::cout<<"array\n"; else std::cout<<"int\n"; } int main() { int a = 6; std::array<int, 4> arr = {1,2,3,4}; SetCoordinates<decltype(a)>(); SetCoordinates<decltype(arr)>(); return 0; }
The std::is_array does not include the case of std::array; Rather, it only checks if the type is just a normal array type(i.e T[], T[N]). Hence, your if statement lands in the false branch. You have to provide a custom traits for the std::array for this to happen: #include <type_traits> // std::true_type, std::false_type, std::is_array template <typename T> struct is_std_array : std::false_type{}; template < typename T, std::size_t N> struct is_std_array<std::array<T, N> > : std::true_type { }; template <typename T> inline static void constexpr SetCoordinates() { if (std::is_array<T>::value || is_std_array<T>::value) // ^^^^^^^^^^^^^^^^^^^^^^^^^-->and check std::cout << "array\n"; else std::cout << "int\n"; } See a demo
72,198,057
72,199,333
use a signal between 2 classes Qt
I have a MainWindow class which contain a QComboBox and a widget which is from another class. This second class contain a QCheckBox and a QComboBox. I want to use a signal to change the checkState of my QCheckBox and the string displayed in my QComboBox from my widget class when the string displayed in my QComboBox from my MainWindow has changed. But I don't really understand which form my signal must have and how I can use it in my widget class. MainWindow.h : #ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QWidget> #include <QComboBox> #include "devices_left_widget.h" #define STRING_DEVICE1 "DEVICE1" #define STRING_DEFAULT "" class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget* parent = nullptr); signals: public slots: void carte_OK(); protected: QComboBox* carte_type_combo_box; devices_left_widget* left_widget; }; #endif // MAINWINDOW_H device_left_widget.h : #ifndef DEVICE_LEFT_WIDGET_H #define DEVICE_LEFT_WIDGET_H #include <QWidget> #include <QCheckBox> #include <QComboBox> #define STRING_DEVICE1 "DEVICE1" #define STRING_DEFAULT "" class device_left_widget : public QWidget { Q_OBJECT public: explicit device_left_widget(QWidget* parent = nullptr); signals: public slots: protected: QGridLayout* main_grid_layout; QCheckBox* device_checkbox; QComboBox* device_type_combo_box; }; #endif // DEVICES_LEFT_WIDGET_H
Let's call your widget's name container. We want to connect QComboBox's currentTextChanged(const QString &text) signal to the widget, so we create a slot that corresponds to the signal, let it be chosenTextChanged(const QString& text). We connect them inside MainWindow constructor: connect(ui->comboBox, SIGNAL(currentTextChanged(const QString &)), ui->container, SLOT(chosenTextChanged(const QString &))); And inside your container class, define the slot as public: public slots: void chosenTextChanged(const QString &text) { //change your QCheckBox's state and //change your QComboBox's text }
72,198,503
72,201,908
Why is a FILE* pointer zero-initialized in C++'s default initialization?
Consider #include <iostream> #include <cstdio> using namespace std; struct Foo { FILE* fp; Foo* mp; }; int main() { Foo f1; // default initialization cout << f1.fp << '\t' << f1.mp << '\n'; Foo f2{}; // zero initialization / direct-list-initialization //Foo f2 = {}; // zero initialization / copy-list-initialization cout << f2.fp << '\t' << f2.mp << '\n'; FILE* fp; // local POD variable, undefined cout << fp << '\n'; } Compilation and execution, g++ tp.cc && ./a.out gives something like: 0 0x5639eb8f00c0 0 0 0x5639eb8f02f0 Both FILE* fp and Foo* mp are of pointer types, thus also of POD types. So, in the default initialization (line Foo f1;), both should be not initialized. But the result, however, appears to suggest the FILE* fp is zero-initialized. How come? Is FILE* a special pointer type that the compiler loves to (zero) initialize, but refuses to zero initialize other pointers?
You didn't initialize the pointers. They get random (undefined) values (specifically, whatever the runtime happened to leave on the stack during initialization before main was called). Sometimes those values happen to be NULL. C++ didn't initialize them, you just got "lucky". As noted in the comments on your question, on different compilers, or with different variable declaration orders, the FILE* often ends up non-NULL, because it's not being initialized, just inheriting whatever happened to already be on the stack.
72,198,985
72,199,278
How does this way of computing array-length work?
i am new to c++ and stumbled upon this way of computing the length of an array with pointers which i don't exactly understand. I looked everywhere but nowhere seems to be an explanation on how it works, i just heard that it's supposed to be a bad way of computing array length but why is that and how does it even work? The code would look something like this: int array[4] = [0, 1, 2, 3] //... int length = *(&array + 1) - array As far as i've tried, it really seems to work, but i don't exactly understand why. I know a bit of pointer logic but this statement seems really odd to me, because you're essentially taking the address of the array (the first element i suppose) and adding one to it (i can imagine that that will give you the address after the last element, but then i don't understand why you would dereference it). And what confuses me most, is that this all gets substracted with the array itself?! Without an index or anything. It would really help when someone would be able to explain that to me, and why it's supposed to be bad exactly. Thanks.
&array This is a pointer to the object array. It is a singular object of an array type. &array + 1 Adding a number to a pointer produces a pointer to a successive sibling of the object in an array of objects. Adding 1 produces the next sibling. For purposes of this pointer arithmetic, singular objects are treated as array of single object. Hence, adding 1 is allowed and it produces a pointer past the end of the figurative array. *(&array + 1) Strictly speaking, this indirects through a pointer past the end, and it may be argued that the behaviour of the program is undefined. But let's assume that's not a problem. The indirection operation produces an lvalue to the (non-existent) object at the address after the array. *(&array + 1) - array Here, the operands of the subtraction are lvalues to arrays. One is the actual array and the other is a hypothetical sibling element in a hypothetical array of arrays. In this case, those arrays implicitly convert to a pointer to first element of the respective arrays. Technically, the subtraction between the converted pointers is undefined because they are pointers to elements of separate arrays, so arguably the behaviour of the program is undefined for yet another reason. But let's assume that's not a problem. The result of subtracting pointers to two elements of the same array produces the distance of the elements. The distance between first elements of adjacent arrays is exactly the number of elements in the first array. why it's supposed to be bad exactly. Notice the parts in previous sections that say behaviour of the program is undefined. That's bad. Also, you had a problem understanding what it does. That's bad. Recommended way to get the size of an array is to use std::size(array).
72,199,097
72,199,508
Why does this boolean function return true (74) and the program display 74?
I am just messing around with the function and somehow palindromes returns 74. I am using Visual studio 2022. Was it supposed to not return anything and catch compiler error since false is never returned in the case below? bool palindromes(string str) { if (str.length() == 0 || str.length() == 1) return true; if (str[0] == str[str.length() - 1]) palindromes(str.substr(1, str.length() - 2)); else return false; } int main() { cout << palindromes("lol"); }
Seems that you ignored the warning: warning C4715: 'palindromes': not all control paths return a value This is a sin.
72,199,799
72,228,324
Are accents and special characters broken in Qt6?
I've got a Qt program that reads from csv files and saves the info into a database. There was no problem until i tried to update from Qt 5.15.2 to Qt 6.3. Now, when I read from the files, all accents are converted to a question mark. I've tried using pretty much every way to explicitly interpret a QTextStream or convert a QString text to Utf-8 or Unicode in general and they all failed to work. Is this a known issue in Qt 6 (because accents worked perfectly in Qt 5.15.2)? Thanks in advance. As requested here's the fragment that reads the csv files: QFile file(path); file.open(QIODevice::ReadOnly | QIODevice::Text); QTextStream in(&file); while (in.readLineInto(&line)){ QStringList separatedLine = line.split("\t"); qDebug() << separatedLine; //do things and save data in database } The issue I have is that this works perfectly if I compile it with Qt5.15.2 but not in Qt6.3.0. Reading the exact same .csv file the following is debbuged: //Original line 34111514 TARJETA COMUNICACIÓN TMB-251 TMB251 //Qt 5.15.2 qDebug outputs QList("34111514", "TARJETA COMUNICACIÓN TMB-251", "TMB251") //Qt 6.3 qDebug outputs QList("34111514", "TARJETA COMUNICACI?N TMB-251", "TMB251") I highly doubt it's a problem with the csv file formatting because it works fine in older Qt.
Okay so after a couple more days of research and trying things it now works. I cannot reproduce the issue but something must have had happened when I used LibreOffice Calc to save the csv encoded as UTF-8 or when I sent that file by email. I suppose the encoding might have gotten in some way changed or corrupted into something that, for some reason, Qt5.15.2 could interpret but Qt6.3 couldn't. I fixed the issue by using Notepad++ to encode the file as UTF-8 again.
72,200,625
72,200,841
Compiler macro to compare byte size of types
Can this if-statement be replaced with a #if .... macro? Possibly without having to include (too many) extra headers. #include <cstdint> #include <string> ///Parse a string to obtain a fixed width type inline uint64_t stou64(const std::string& in) { if (sizeof(unsigned long) == sizeof(uint64_t)) { return std::stoul(in); } else { return std::stoull(in); } }
You don't need pre-processor macro for this. The function is well-defined regardless of the size, and the compiler is smart enough to optimise the unused branch away completely. If you want to be sure that the unused branch is removed even with optimisation disabled, you can use if constexpr. Simply add constexpr after if in your example. If you don't need to support currently active locale, then consider using std::from_chars instead.
72,201,109
72,201,617
C++ multiple nested template types inside outer template class referring to each other
I am quite new to C++ and I am trying to code a simple version of a list (doubly linked as in STL). The list has a template parameter. Inside the list I define two nested classes, also with different template parameters. Now, I agree, in this case defining the inner classes as templates is completely useless because their use is to the outer class template type; but this for me an intellectual exercise more than anything else, to learn more about C++. With that said, I am trying to define member functions outside the scope of the class. My IDE says that the prototype for the Iterator constructor inside the NodeList class with argument does not match my definition. So first of all, the type is not recognized and why is that happening. Secondly, how do I achieve what I am trying to do? Thanks a lot in advance template <typename T> class NodeList { typedef T value_type; public: template <typename E> class Iterator { template <typename> friend class NodeList; public: E& operator*(); bool operator==(const Iterator&) const; bool operator!=(const Iterator&) const; Iterator& operator++(); Iterator operator++(int); Iterator& operator--(); Iterator operator--(int); private: NodeList<E>::Node<E> *node; Iterator(NodeList<E>::Node<E> *node); }; private: template <typename E = value_type> struct Node { E element; Node<E> *prev; Node<E> *next; }; }; template <typename T> template<typename E> NodeList<T>::Iterator<E>::Iterator(NodeList<T>::Node<E> *node) { }
Two things wrong with that code: 1 You can't use Node before it is declared. So move that private block up top. 2 NodeList<E>::Node<E> must be NodeList<T>::Node<E>, or simply Node<E> as you are already in the Nodelist<T> class. template <typename T> class NodeList { typedef T value_type; template <typename E = value_type> struct Node { E element; Node<E> *prev; Node<E> *next; }; public: template <typename E> class Iterator { template <typename> friend class NodeList; public: E& operator*(); bool operator==(const Iterator&) const; bool operator!=(const Iterator&) const; Iterator& operator++(); Iterator operator++(int); Iterator& operator--(); Iterator operator--(int); private: Node<E> *node; Iterator(Node<E> *node); }; }; template <typename T> template <typename E> NodeList<T>::Iterator<E>::Iterator(NodeList<T>::Node<E> *node) { } I can think of cases where a Nodelist<E>::Node<E> could be a desired in the subclass or even the class itself but that either needs a different syntax or maybe isn't even supported. But I think in this case Nodelist<T>::Node<E> is actually the desired type.
72,201,421
72,201,606
How to do is >> std::skipws >> through multiple indices of an array?
Let's say you have std::array<int, SIZE> a, and you have saved each element of a into a file in one line separated by a space. Then you want to read them with a std:istream& is via: is >> std::skipws >> a[0] >> a[1] >> a[2] >> ... >> a[SIZE-1]; How to write this generically for any value of SIZE. Even though there are other easy ways of doing this, I'm curious how it is done with this particular method.
How to write this generically for any value of SIZE. There are control structures for repeating an operation a variable number of times: loops. For example: is >> std::skipws; for(auto& el : a) { is >> el; }
72,201,447
72,201,505
Template template argument mismatch
The following code #include <cstdint> template<typename T> struct allo{}; template <typename T, std::size_t a = alignof(T)> struct AA{ constexpr std::size_t align() { return a; } }; template<template <typename> typename AT> struct SAR{ }; using UHR = SAR<allo>; using AHR = SAR<AA>; int main() { UHR u; AHR a; return 0; } is accepted by GCC with -std=c++17, but rejected by GCC with std=c++14 and clang (regardless of the C++ dialect). https://godbolt.org/z/xaE56Y5Pj Which compiler is right? Is this some change in C++17 that clang hasn't implemented?
Before C++17, template template parameters must use class instead of typename. In C++17, this restriction got lifted and the keywords are equivalent in this context. Your issue is actually that AA has two template parameters and you try to bind it to AT which as one. C++17 allowed templates with N non-defaulted parameters to act the same as templates with N parameters in total. But clang has not implemented it yet by default, you can use -frelaxed-template-template-args flag as per the answer.
72,201,979
72,203,340
Combining regex and ranges causes memory issues
I wanted to construct a view over all the sub-matches of regex in text. Here are two ways to define such a view: char const text[] = "The IP addresses are: 192.168.0.25 and 127.0.0.1"; std::regex regex{R"((\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3}))"}; auto sub_matches_view = std::ranges::subrange( std::cregex_iterator{std::ranges::begin(text), std::ranges::end(text), regex}, std::cregex_iterator{} ) | std::views::join; auto sub_matches_sv_view = std::ranges::subrange( std::cregex_iterator{std::ranges::begin(text), std::ranges::end(text), regex}, std::cregex_iterator{} ) | std::views::join | std::views::transform([](std::csub_match const& sub_match) -> std::string_view { return {sub_match.first, sub_match.second}; }); sub_matches_view's value type is std::csub_match. It is created by first constructing a view of std::cmatch objects (via the regex iterator), and since each std::cmatch is a range of std::csub_match objects, it is flattened with std::views::join. sub_matches_sv_view's value type is std::string_view. It is identical to sub_matches_view, except it also wraps each element of sub_matches_view in a std::string_view. Here's an usage example of the above ranges: for(auto const& sub_match : sub_matches_view) { std::cout << std::string_view{sub_match.first, sub_match.second} << std::endl; // #1 } for(auto const& sv : sub_matches_sv_view) { std::cout << sv << std::endl; // #2 } Loop #1 works without problems - the printed results are correct. However, loop #2 causes heap-use-after-free issues according to the Address Sanitizer. In fact, just looping over sub_matches_sv_view without accessing the elements at all causes this problem too. Here is the code on Compiler Explorer as well as the output of the Address Sanitizer. I am out of ideas as to where my mistake is. text and regex never go out of scope, I don't see any iterators that might be accessed outside of their lifetimes. The std::csub_match object holds iterators (.first, .second) into text, so I don't think it needs to remain alive itself after constructing the std::string_view in std::views::transform. I know there are many other ways to iterate over regex matches, but I am specifically interested in what's causing the memory bugs in my program, I don't need work-arounds for this issue.
The problem is std::regex_iterator and the fact that it stashes. That type basically looks like this: class regex_iterator { vector<match> matches; public: auto operator*() const -> vector<match> const& { return matches; } }; What this means, for instance, is that even though this iterator's reference type is T const&, if you have two copies of the same iterator, they'll actually give you references into different objects. Now, join_view<R>::iterator basically looks like this: class iterator { // the iterator into the range we're joining iterator_t<R> outer; // an iterator into *outer that we're iterating over iterator_t<range_reference_t<R>> inner; }; Which, for regex_iterator, roughly looks like this: class iterator { // the regex matches vector<match> outer; // the current match match* inner; }; Now, what happens when you copy this iterator? The copy's inner still refers to the original's outer! These aren't actually independent in the way that you'd expect. Which means that if the original goes out of scope, we have a dangling iterator! This is what you're seeing here: transform_view ends up copying the iterator (as it is certainly allowed to do), and now you have a dangling iterator (libc++'s implementation moves instead, which is why it happens to work in this case as 康桓瑋 pointed out). But we can reproduce the same issue without transform as long as we copy the iterator and destroy the original. For instance: #include <ranges> #include <regex> #include <iostream> #include <optional> int main() { std::string_view text = "The IP addresses are: 192.168.0.25 and 127.0.0.1"; std::regex regex{R"((\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3}))"}; auto a = std::ranges::subrange( std::cregex_iterator(std::ranges::begin(text), std::ranges::end(text), regex), std::cregex_iterator{} ); auto b = a | std::views::join; std::optional i = b.begin(); std::cout << std::string_view((*i)->first, (*i)->second) << '\n'; // fine auto j = *i; i.reset(); std::cout << std::string_view(j->first, j->second) << '\n'; // boom } I'm not sure what a solution to this problem would look like, but the cause is the std::regex_iterator and not the views::join or the views::transform.
72,202,639
72,202,932
GPS Coordinates in 4 bytes
I am trying to find a method to store the standard Latitude and Longitude (double---both of 8 bytes) in 4 bytes, and viceversa (i.e. convert these data in the standard 8 byte latitude/longitude). Honestly, it is not clear how to do that. I am programming in C++, so if there is an existing function or library to do that, it would be good.
Fixed point rational representation is a potential solution for this purpose. There is no fundamental type for fixed point rational numbers, nor does the standard library provide types implementing them. The idea is fairly simple however: Scale the value of an underying integer such that the range of the underlying integer is mapped to the desired range of values.
72,204,397
72,209,557
Visual C++ 6.0 - Possible Conversion Loss of Data (Warning C4244)
I am using quite an old compiler, and I believe the compiler has made a bit of a mistake in its warning diagnosis. typedef unsigned char uint8_t; // 8-bit byte typedef unsigned int uint32_t; // 32-bit word (change to "long" for 16-bit machines) typedef struct _sha256_ctx_t { uint8_t data[64]; uint32_t data_len; unsigned __int64 bit_len; // unsigned long long uint32_t state[8]; } sha256_ctx_t; void crypto_sha256_final(sha256_ctx_t *ctx, uint8_t *digest) { uint32_t i; i = ctx->data_len; // Append to the padding the total message's length in bits and transform. ctx->bit_len += ctx->data_len * 8; ctx->data[63] = ctx->bit_len; // LINE 156 IS HERE! ctx->data[62] = ctx->bit_len >> 8; ctx->data[61] = ctx->bit_len >> 16; ctx->data[60] = ctx->bit_len >> 24; ctx->data[59] = ctx->bit_len >> 32; ctx->data[58] = ctx->bit_len >> 40; ctx->data[57] = ctx->bit_len >> 48; ctx->data[56] = ctx->bit_len >> 56; // LINE 163 IS HERE! local_sha256_transform(ctx, ctx->data); // Since this implementation uses little endian byte ordering and SHA uses big endian, // reverse all the bytes when copying the final state to the output digest. for (i = 0; i < 4; ++i) { digest[i] = (ctx->state[0] >> (24 - i * 8)) & 0x000000ff; digest[i + 4] = (ctx->state[1] >> (24 - i * 8)) & 0x000000ff; digest[i + 8] = (ctx->state[2] >> (24 - i * 8)) & 0x000000ff; digest[i + 12] = (ctx->state[3] >> (24 - i * 8)) & 0x000000ff; digest[i + 16] = (ctx->state[4] >> (24 - i * 8)) & 0x000000ff; digest[i + 20] = (ctx->state[5] >> (24 - i * 8)) & 0x000000ff; digest[i + 24] = (ctx->state[6] >> (24 - i * 8)) & 0x000000ff; digest[i + 28] = (ctx->state[7] >> (24 - i * 8)) & 0x000000ff; } } That code results in this error (from lines 156 to 163): SHA256.cpp(156) : warning C4244: '=' : conversion from 'unsigned __int64' to 'unsigned char', possible loss of data I guess this old compiler doesn't realise that adding it with 0xFF narrows the result to a byte. Does anyone have a suggestion on how to get around the false warning? Original code source: https://programmer.group/61737ba233df9.html
There's nothing wrong with the compiler in this case ctx->data[63] = ctx->bit_len; // LINE 156 IS HERE! ctx->data[62] = ctx->bit_len >> 8; ctx->data[61] = ctx->bit_len >> 16; ctx->data[60] = ctx->bit_len >> 24; ctx->data[59] = ctx->bit_len >> 32; ctx->data[58] = ctx->bit_len >> 40; ctx->data[57] = ctx->bit_len >> 48; ctx->data[56] = ctx->bit_len >> 56; // LINE 163 IS HERE! ctx->bit_len is a 64-bit type so obviously storing it into a uint8_t doesn't work. There's no masking with 0xFF in those lines like in digest[i] = (ctx->state[0] >> (24 - i * 8)) & 0x000000ff;. The only case where it's lacking analysis is ctx->data[56] = ctx->bit_len >> 56 because the result fits in a uint8_t. To get the LSB you need to do an explicit cast so that the compiler knows what you're doing ctx->data[62] = uint8_t(ctx->bit_len >> 8); That said, there's no need to copy manually like that, just use memcpy and ntohll. The code isn't good and using an ancient compiler is even worse. There are lots of good crypto libraries nowadays that use proper SIMD and multithreading like OpenSSL
72,204,426
72,204,493
Destroying/removing a static text in c++ win32
I am using win32 API in c++ and I have a static piece of text. How would I delete the static text when the user presses a button? I can't figure out to do that.
Assuming you have the window handle hwnd of the STATIC control, you can delete it via DestroyWindow(hwnd) or simply make it not be visible with ShowWindow(hwnd, SW_HIDE).
72,204,846
72,204,914
How to Fix MISRA C++ Rule 0-1-4
The following code violates the MISRA C++ rule 0-1-4: for (auto &a : b) { ... // The variable a is used only in the for condition. } Rule: A project shall not contain non-volatile POD variables having only one use. Variable 'a' is used only once, that is, during initialization. What I tried: for (const auto &a : b) { ... // The variable a is used only in the for condition. } But that was not the solution. Does anyone have an idea how I can fix it?
Alas the current C++ grammar requires you to declare a variable when using the range-for form of the for loop: for (auto& : b) { is not allowed, despite it having potential applications (such as computing the number of elements in a container). Writing a; or (void)a; in the loop body might work depending on the type. This would fool the static analyser and you can hope the expression gets compiled out.
72,204,862
72,204,942
What is this std::string constructor doing?
I am trying to write a native host client for a WebExtension browser addon in C++. I looked for examples and unfortunately only found a couple ones. There's this simple good looking one I'm following but I don't understand the part where a string is constructed as follows: json get_message() { char raw_length[4]; fread(raw_length, 4, sizeof(char), stdin); uint32_t message_length = *reinterpret_cast<uint32_t*>(raw_length); if(!message_length) exit(EXIT_SUCCESS); char message[message_length]; fread(message, message_length, sizeof(char), stdin); string m( message, message + sizeof message / sizeof message[0] ); return json::parse(m); } I looked at multiple documentations for C++ std::string constructors but I can't figure what is going on here exactly. What does string m( message, message + sizeof message / sizeof message[0] ); do? And why not just do string m(message)? There is also the char message[message_length]; line which confused me because message_length is not a constant but apparently this is a GCC-specific feature.
What does string m( message, message + sizeof message / sizeof message[0] ); do? message decays to pointer to first element, sizeof message / sizeof message[0] is the number of elements in the array, and message + sizeof message / sizeof message[0] is a pointer to the past the end of the array. Note that this is unnecessarily convoluted way to get the number of elements. I would recommend using message + message_length instead. The constructor copies all characters from the range between these iterators (pointers). The iterators span the entire array. What I don't understand is I can't seem to find a std::string constructor that accepts (char*, char*) The constructor looks like this (simplified): template<class InputIt> string(InputIt first, InputIt last); The template parameter is deduced to be char* from the arguments. And why not just do string m(message)? That constructor requires that message is terminated by null character. If the argument isn't terminated by null character, then the behaviour of the program would be undefined. That would be bad. Also, if the array does contain null terminator characters, then that constructor would not copy those into the string, while the iterator range constructor does. That would be bad if the intention is to copy the null terminators. There is also the char message[message_length]; line which confused me because message_length is not a constant This isn't allowed in C++. The program is ill-formed. Since the example is rather poor quality, here is a version that fixes major issues: json get_message(std::istream& in) { std::uint32_t message_length; // NOTE input is assumed to be in native byte order in.read(reinterpret_cast<char*>(&message_length), sizeof message_length); if (!in) throw std::runtime_error("Invalid message length"); if (!message_length) throw std::runtime_error("No input"); std::string m('\0', message_length); in.read(m.data(), message_length); if (!in) throw std::runtime_error("Invalid message"); return json::parse(m); } You can adjust if you want to use another error handling instead of exceptions. The demonstrated error handling has room for improvement (unique exception classes etc.). Most significant deviation from the original example is that the function can read from any input stream; not only standard input. I've chosen to do so not only because it's more general, but also because there's actually no standard+portable way to read binary from standard input. See C read binary stdin
72,204,957
72,205,281
Changing a macro in C (or C++)
In other words, how can I redefine a macro based on it's previous definition? Specifically, I want to add a string to the end of a string macro in C++. This is what I've tried so far: #define FOO "bla" // code here will read FOO as "bla" #define FOO FOO ## "dder" // code here will read FOO as "bladder" In C++, this returns error: FOO was not declared in this scope. How would I do this without getting this error? EDIT: I've read the comments and found out what an "XY problem" is. What I want to do is make a library for C but the library is written in C++. Because the library requires Classes to function (because it uses other C++ libraries), I wanted to make an empty class that the C program using the library can add custom properties to using Macro functions. Something like this: // lib.h #define PROPERTIES "" #define NEW_PROPERTY(X) // add X + ";\n" to PROPERTIES (somehow) #ifdef __cplusplus Class myclass { public: PROPERTIES } #endif _ // c code #include <lib.h> NEW_PROPERTY(int id); NEW_PROPERTY(int color); int main(){ ... The c program won't need to access the properties because they only exist so that a third-party library that is a dependency for my library can use them.
This is not possible. From the gcc documentation (emphasis is mine): However, if an identifier which is currently a macro is redefined, then the new definition must be effectively the same as the old one. Two macro definitions are effectively the same if: Both are the same type of macro (object- or function-like). All the tokens of the replacement list are the same. If there are any parameters, they are the same. Whitespace appears in the same places in both. It need not be exactly the same amount of whitespace, though. Remember that comments count as whitespace. These definitions are effectively the same: #define FOUR (2 + 2) #define FOUR (2 + 2) #define FOUR (2 /* two */ + 2) but these are not: #define FOUR (2 + 2) #define FOUR ( 2+2 ) #define FOUR (2 * 2) #define FOUR(score,and,seven,years,ago) (2 + 2) If a macro is redefined with a definition that is not effectively the same as the old one, the preprocessor issues a warning and changes the macro to use the new definition. If the new definition is effectively the same, the redefinition is silently ignored. This allows, for instance, two different headers to define a common macro. The preprocessor will only complain if the definitions do not match.
72,205,026
72,205,171
Why do I get an error when I overload the << on the object returned by the + operator overloaded function
class String { char* array; public: String(const char* s) { array = new char[strlen(s) + 1]{ '\0' }; strcpy(array, s); } ~String() { if (array) { delete[]array; } } String operator+ (const char* p) //返回对象 { String temp(p); char* tempStr = temp.array; temp.array = new char[strlen(array) + strlen(tempStr) + 1]{ '\0' }; strcpy(temp.array, array); strcat(temp.array, p); delete[]tempStr; return temp; } friend ostream& operator<<(ostream& output, String& x); // <<函数重载只能定义成友元 }; ostream& operator << (ostream& output, String& x) //对<<重载的方式 { output << x.array; return output; } int main() { String string1("mystring"); cout << string1 + "ab" << endl; cout << string1 << endl; return 0; } This is my first time asking a question here, so please forgive me if there are any bad descriptions :) Back to the point ,I have overloaded + and << operators,so I want to get the output "mystringab" by cout<<string1+"ab"<<endl,but the output is garbled. I think there may be a problem with the + operator overloaded function,can someone please tell me where is the problem? And if I want to get the correct result, how should I rewrite the overloaded function?
The problem is that the second parameter to overloaded operator<< cannot be bound to an String rvalue since the second parameter is an lvalue reference to a non-const String. how should I rewrite the overloaded function? You need to make the second parameter to overloaded operator<< a const String& so that it can work with the second argument "ab" as well, as shown below: //---------------------------------------- vvvvv------------>low-level const added here friend ostream& operator<<(ostream& output,const String& x); Similarly do the same in the definition: //----------------------------------- vvvvv------------>low-level const added here ostream& operator << (ostream& output,const String& x) { output << x.array; return output; } Also, make sure that your program don't have any undefined behavior. For example, by making sure that you use delete or delete[] only when it is safe to do so(that data to which the pointer points is no longer needed). You can use tools such as valgrind to detect some basic problems.
72,205,459
72,205,676
How can I access public constructor of private nested class C++
I have a nested private classes Nested and Key and I want that I could using my add_new_object(Key, Nested) function add objects to my my_mmap multimap. But when I try to call that those classes constructors, obviously that it's inaccessible. How can I solve the problem. class Enclosing { private: class Nested { string m_str; double m_dbl; bool m_boolean; public: Nested(string str, double dbl, bool boolean) :m_str(str), m_dbl(dbl), m_boolean(boolean) {}; }; class Key { int m_number; string m_name; public: Key(int num, string name) :m_number(num), m_name(name) {}; }; Enclosing* singleton; std::multimap<Key, Nested> my_mmap; public: void add_new_object_to_mmap(Key k, Nested n) {} static Enclosing* get_singleton() { static Enclosing instance; return &instance; } }; Thank you all in advance!
You seem to misunderstand what it means to declare a type in the private section. Or at least you are not aware of the implications of those types appearing as arguments of a public member function. Here is your code with definitions added (without a definition for Key and Nested you cannot call their constructor at all): #include <map> class Enclosing { private: class Nested {}; class Key {}; Enclosing* singleton; std::multimap<Key, Nested> my_mmap; public: void add_new_object_to_mmap(Key k, Nested n) {} static Enclosing* get_singleton() { static Enclosing instance; return &instance; } }; Because the type Key and Nested appear in the public interface of Enclosing they are not actually private. Only their names are private. It is possible to infer the two types from the member function: template <typename F> struct get_types; template <typename K,typename N> struct get_types< void(Enclosing::*)(K,N)> { using Key = K; using Nested = N; }; Now you can call their constructor like you call the constructor of any other type: int main() { using Types = get_types<decltype(&Enclosing::add_new_object_to_mmap)>; using Key = Types::Key; using Nested = Types::Nested; Enclosing::get_singleton()->add_new_object_to_mmap(Key{},Nested{}); } Complete Example Finally, note that the caller doesn't even have to have names for the two types. This works as well (or with parameters when there are no default constructors): Enclosing::get_singleton()->add_new_object_to_mmap({},{}); A type declared in the private section of another class is not private when it appears in the public interface. If you really wanted to hide the two types from the user of Enclosing then you need to do something else. See Teds answer for how to pass only parameters to be passed to their constructor to the public add_new_object_to_mmap. Then the two types can be truly private.
72,205,522
72,205,873
GLIBCXX_3.4.29 not found
I am trying to install mujuco onto my linux laptop and everything works until I try to import it into a python file. When I try to import it/run a python script that already has mujuco in it I get the following errors: Import error. Trying to rebuild mujoco_py. running build_ext building 'mujoco_py.cymj' extension gcc -pthread -B /home/daniel/miniconda3/envs/mujoco_py/compiler_compat -Wl,--sysroot=/ -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -I/home/daniel/.mujoco/mujoco-py/mujoco_py -I/home/daniel/.mujoco/mujoco210/include -I/home/daniel/miniconda3/envs/mujoco_py/lib/python3.8/site-packages/numpy/core/include -I/home/daniel/miniconda3/envs/mujoco_py/include/python3.8 -c /home/daniel/.mujoco/mujoco-py/mujoco_py/cymj.c -o /home/daniel/.mujoco/mujoco-py/mujoco_py/generated/_pyxbld_2.1.2.14_38_linuxcpuextensionbuilder/temp.linux-x86_64-3.8/home/daniel/.mujoco/mujoco-py/mujoco_py/cymj.o -fopenmp -w gcc -pthread -B /home/daniel/miniconda3/envs/mujoco_py/compiler_compat -Wl,--sysroot=/ -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -I/home/daniel/.mujoco/mujoco-py/mujoco_py -I/home/daniel/.mujoco/mujoco210/include -I/home/daniel/miniconda3/envs/mujoco_py/lib/python3.8/site-packages/numpy/core/include -I/home/daniel/miniconda3/envs/mujoco_py/include/python3.8 -c /home/daniel/.mujoco/mujoco-py/mujoco_py/gl/osmesashim.c -o /home/daniel/.mujoco/mujoco-py/mujoco_py/generated/_pyxbld_2.1.2.14_38_linuxcpuextensionbuilder/temp.linux-x86_64-3.8/home/daniel/.mujoco/mujoco-py/mujoco_py/gl/osmesashim.o -fopenmp -w gcc -pthread -shared -B /home/daniel/miniconda3/envs/mujoco_py/compiler_compat -L/home/daniel/miniconda3/envs/mujoco_py/lib -Wl,-rpath=/home/daniel/miniconda3/envs/mujoco_py/lib -Wl,--no-as-needed -Wl,--sysroot=/ /home/daniel/.mujoco/mujoco-py/mujoco_py/generated/_pyxbld_2.1.2.14_38_linuxcpuextensionbuilder/temp.linux-x86_64-3.8/home/daniel/.mujoco/mujoco-py/mujoco_py/cymj.o /home/daniel/.mujoco/mujoco-py/mujoco_py/generated/_pyxbld_2.1.2.14_38_linuxcpuextensionbuilder/temp.linux-x86_64-3.8/home/daniel/.mujoco/mujoco-py/mujoco_py/gl/osmesashim.o -L/home/daniel/.mujoco/mujoco210/bin -Wl,-R/home/daniel/.mujoco/mujoco210/bin -lmujoco210 -lglewosmesa -lOSMesa -lGL -o /home/daniel/.mujoco/mujoco-py/mujoco_py/generated/_pyxbld_2.1.2.14_38_linuxcpuextensionbuilder/lib.linux-x86_64-3.8/mujoco_py/cymj.cpython-38-x86_64-linux-gnu.so -fopenmp Traceback (most recent call last): File "setting_state.py", line 7, in <module> from mujoco_py import load_model_from_xml, MjSim, MjViewer File "/home/daniel/.mujoco/mujoco-py/mujoco_py/__init__.py", line 2, in <module> from mujoco_py.builder import cymj, ignore_mujoco_warnings, functions, MujocoException File "/home/daniel/.mujoco/mujoco-py/mujoco_py/builder.py", line 504, in <module> cymj = load_cython_ext(mujoco_path) File "/home/daniel/.mujoco/mujoco-py/mujoco_py/builder.py", line 111, in load_cython_ext mod = load_dynamic_ext('cymj', cext_so_path) File "/home/daniel/.mujoco/mujoco-py/mujoco_py/builder.py", line 130, in load_dynamic_ext return loader.load_module() ImportError: /home/daniel/miniconda3/envs/mujoco_py/bin/../lib/libstdc++.so.6: version `GLIBCXX_3.4.29' not found (required by /lib/x86_64-linux-gnu/libOSMesa.so.8) [1]: https://i.stack.imgur.com/gUhXI.png I have gcc 11.0.2 installed and I'm using python3.8 in my virtual environment. Here are my exact steps https://docs.google.com/document/d/1eBvfKoczKmImUgoGMbqypODBXmI1bD91/edit Everything works accordingly until the very last step where I try to run an actual python module I really don't know why this is happening and I've tried just about everything on the internet. I would really appreciate it if someone can help.
Where does /home/daniel/miniconda3/envs/mujoco_py/lib/libstdc++.so.6 come from? Something bundles a version of libstdc++.so.6 which is older than your system version, and other system libraries depend on the newer version. You should be able to fix this issue by just deleting the file in your home directory.
72,205,650
72,207,035
How to create constructor for braced-init-list in c++ without standard library?
I would like to be able to initialize my objects with a brace-init-list: #include <initializer_list> template <class T> struct S { T v[5]; S(std::initializer_list<T> l) { int ind = 0; for (auto &&i: l){ v[ind] = i; ind++; } } }; int main() { S<int> s = {1, 2, 3, 4, 5}; } As I found out here: https://en.cppreference.com/w/cpp/utility/initializer_list, it is necessary to use the standard library for this. But that is strange for me. I would suggest that such initialization is a part of the C++ syntax. Is it possible to create a constructor without use of std:initializer_list? Edit: It could be useful for programming embedding devices where standard library is not available (e.g. Arduino AVR).
As a work around one could do something like #include <iostream> template <class T> struct S { T v[5]; template<typename... Args> requires (std::same_as<T, Args> && ...) S(Args... args) { static_assert(sizeof...(args) <= 5); int ind = 0; ((v[ind++] = args), ...); } }; int main() { S<int> s = {1, 2, 3, 4, 5}; for ( auto e : s.v ) { std::cout << e << ' '; } } live on godbolt As RemyLebeau pointed out in the comments a constructor like S(T,T,T,T,T) is needed. With a variadic constructor template and C++17 fold expressions you can make the compiler provide a constructor of that form for each number of arguments. Note that the requires constraint (C++20) is important if you want other constructors in that class. It constraints the template the form S(T,T,T,...) and will not take part in overload resolution for arguments, that are not all of type T. It should also be possible to achieve that pre C++20 with std::enable_if*. Also remember that the compiler will instantiate a constructor with matching signature for each call with a different number of arguments. Thus this could result in code bloat if used often and with many different numbers of arguments in the braces. * like this for example: template<typename... Args, typename std::enable_if_t<(std::is_same_v<T, Args> && ...), bool> = true> S(Args... args) { //... }
72,206,078
72,206,168
What will happen if I pass a mutable lambda to a function as const reference?
What does the code actually do when I pass a mutable lambda as const reference? Why does not the compiler raise error, is this an undefined operation? Why f1 and f2 are differnt which f1 uses std::function<void()> and f2 uses auto? I found a similar question but I still don't fully understand A const std::function wraps a non-const operator() / mutable lambda #include <iostream> #include <functional> void call(std::function<void()> const & cb) { cb(); cb(); } int main() { std::function<void()> f1 = [a = 0] () mutable { std::cout << ++a << std::endl; }; call(f1); // prints 1 2 call(f1); // prints 3 4 auto f2 = [a = 0] () mutable { std::cout << ++a << std::endl; }; call(f2); // prints 1 2 call(f2); // prints 1 2 } https://godbolt.org/z/765endY7c
In first case both calls of call(f1) are using same instance of std::function<void()>. In second case call(f2); implicit conversion form lambda to std::function<void()> kicks in and respective temporary object is created. So second call uses new copy of temporary object. Try transform this code in cppinsights to see this with more details. int main() { class __lambda_10_32 { public: inline /*constexpr */ void operator()() { std::cout.operator<<(++a).operator<<(std::endl); } private: int a; public: // inline /*constexpr */ __lambda_10_32(const __lambda_10_32 &) noexcept = default; // inline /*constexpr */ __lambda_10_32(__lambda_10_32 &&) noexcept = default; __lambda_10_32(const int & _a) : a{_a} {} }; std::function<void ()> f1 = std::function<void ()>(__lambda_10_32{0}); call(f1); call(f1); class __lambda_16_15 { public: inline /*constexpr */ void operator()() { std::cout.operator<<(++a).operator<<(std::endl); } private: int a; public: // inline /*constexpr */ __lambda_16_15(const __lambda_16_15 &) noexcept = default; // inline /*constexpr */ __lambda_16_15(__lambda_16_15 &&) noexcept = default; __lambda_16_15(const int & _a) : a{_a} {} }; __lambda_16_15 f2 = __lambda_16_15{0}; call(std::function<void ()>(__lambda_16_15(f2))); call(std::function<void ()>(__lambda_16_15(f2))); return 0; }
72,206,115
72,206,319
Does C++ let a program compiled by itself to return pointer to an array to be used directly?
For example, if I have some code string like this: std::string code = R"( #include<thread> #include<iostream> int main() { int array[@@size@@]; std::cout<<(size_t)&array[0]<<std::endl; std::this_thread::sleep(1000000000); return 0; } )"; boost::replace_all(code, "@@size@@", std::to_string(memSize)); then if I save it to a file programmatically and compile it like this: system("g++ code.cpp"); then run it and parse its output, can I directly use the address to access the array in any way without getting segfault? Does a process have any way of sharing simple arrays to enable faster messaging or other purposes without using any other APIs? I mean, does it have an advantage on having more freedom on accessing it if the program is compiled & run by current process, with C++?
As far as C++ is concerned, there may not even be a concept of processes. They are mentioned in the standard, as far as I can tell, only twice. Once in a recommendation about lock-free atomics, suggesting that they should also work when shared between processes, and once with regards to possible causes of file system races. Anything about actually sharing memory between processes would be operating system dependent, and will therefore likely require some operating system specific API calls.
72,207,077
72,207,226
finding max value of a struct construction inside vector c++
enum class comp { age, weight }; struct person { int age; int weight; static auto max(std::vector<person> x, comp(y)) { if (comp(y) == comp::age) { for (person e : x) { auto max = 0; for (card e : x) { if (max < e) max = e; } } } i am trying to find the max value of age, weight from this vector of a struct construction.
here is a corrected version of your code. As cory post shows you can do this with standard algorithms in a much cleaner way struct person { int age; int weight; static int max(std::vector<person> x, comp y) { if (y == comp::age) { for (person e : x) { auto max = 0; for (auto e : x) { if (max < e.age) max = e.age; } return max; } } return 0; } }; int main() { person p1; person p2; p1.age=42; p2.age=4; std::vector<person> pp{p1,p2}; int maxAge = person::max(pp, comp::age); }
72,207,152
72,207,345
How can change the value of a member of a base class?
I have three classes: class Operation{ public: virtual bool execute(const Solution& sol, Solution& newSol) = 0; pair<int, int> pair_routes; }; class OperationR : public Operation{ public: OperationR(){}; bool execute(const Solution& sol, Solution& newSol); pair<int, int> pair_routes; }; class OperationD : public Operation{ public: OperationD(){}; bool execute(const Solution& sol, Solution& newSol); pair<int, int> pair_routes; }; The value of pair_routes changes inside the execute() function. In the main() function, I create a vector of class Operation like this: vector<Operation*> operations; OperationR* opr = new OperationR(); operations.push_back(opr); OperationD* opd = new OperationD(); operations.push_back(opd); Operation* op = operations[0]; Solution s1, s2; op->execute(s1, s2); // line 1 cout << op->pair_routes.first; There is no problem in the compilation, but even if the value of pair_routes changes in line 1, it returns the value 0. I tried to initialize this member in the base class with different values, and each time the program returns this value.
Your derived classes are declaring their own pair_routes members that shadow (ie, hide) the pair_routes member of the base Operation class. When you execute op->execute(), op is pointing at an OperationR object, so it is calling OperationR::execute(), which is then modifying the OperationR::pair_routes data member. But then afterwards, you are display the Operation::pair_routes data member instead, which was not modified. Get rid of the shadowing pair_routes data members, you don't need them. The derived classes have access to the pair_routes data member of the base class. class Operation{ public: virtual bool execute(const Solution& sol, Solution& newSol) = 0; pair<int, int> pair_routes; }; class OperationR : public Operation{ public: OperationR() = default; bool execute(const Solution& sol, Solution& newSol) override; //pair<int, int> pair_routes; // <-- get rid of this }; class OperationD : public Operation{ public: OperationD() = default; bool execute(const Solution& sol, Solution& newSol) override; //pair<int, int> pair_routes; // <-- get rid of this };
72,207,562
72,207,761
Where is the library for GUID in win32
I was trying the example code on "How to Play Media Files with Media Foundation", and I tried to compile the code with the following makefile: LDFLAGS = -LC:\\pathToWindowsSDK\\Lib\\10.0.22000.0\\um\\x64 -lMfplat -lMfuuid -lUser32 -lOle32 -lShlwapi -lMf default: winmain.o player.o g++ winmain.o player.o -o a.exe winmain.o: winmain.cpp player.h g++ winmain.cpp -c player.o: player.cpp player.h g++ player.cpp $(LDFLAGS) -c and I keep getting the following undefined references: C:/Personal/Soft/mingw/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/11.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: player.o:player.cpp:(.rdata$.refptr.GUID_NULL[.refptr.GUID_NULL]+0x0): undefined reference to `GUID_NULL' C:/Personal/Soft/mingw/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/11.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: player.o:player.cpp:(.rdata$.refptr.MR_VIDEO_RENDER_SERVICE[.refptr.MR_VIDEO_RENDER_SERVICE]+0x0): undefined reference to `MR_VIDEO_RENDER_SERVICE' collect2.exe: error: ld returned 1 exit status make: *** [Makefile:4: default] Error 1 Both are undefined errors of GUID, is there a library that I should link? I'm using MSYS g++ compiler, and Windows 11 SDK (10.0.22000). Thanks in advance!
Try adding -luuid (Visual C++ projects created through Visual Studio link to uuid.lib by default).
72,207,645
72,355,575
Is there a way to teach Android Studio how to display a C++ struct when hovering over the variable?
As a practical example, say I have a struct that looks like this: struct MyFoo { std::string mValue; bool hasValue; MyFoo() : hasValue(false) {} MyFoo(std::string value) : mValue(value), hasValue(true) {} }; If I hover over an instance of this struct, Android Studio displays + ☰ {MyFoo}. I can expand this, and with a little drilling down, see what the contents are. (I should note that this is an oversimplified example; my real-world application is a much more complicated struct, and seeing the value is not very easy). Is there a way to somehow get it to display something like + ☰ {MyFoo} <none> or + ☰ {MyFoo} "Hello, world" instead? I can see Android Studio doing this with some of the STL types, which suggests that somewhere there's knowledge on how to do this. Bonus questions: How about XCode?
As far as I know, Android Studio uses LLDB for debugging native code. You can use LLDB commands to add custom formatting for showing these variables. See: https://lldb.llvm.org/use/variable.html The easiest way to do fancy pretty-printing is a Python script inside LLDB (see the LLDB docs link for more info, I based this example off it) (lldb) type summary add -P MyFoo Enter your Python command(s). Type 'DONE' to end. def function (valobj,internal_dict,options): mval = valobj.GetChildMemberWithName('mValue') hasval = valobj.GetChildMemberWithName('hasValue') if hasval.GetValueAsUnsigned(0) == 0: return '<none>' else: return mval.GetSummary() DONE Dealing with std::string is a real can of worms, but you can find some potential solutions on this question.
72,207,931
72,215,406
Why is my OpenGL texture black (in Dear ImGUI)?
In OpenGL 4.6, I (attempt to) create and initialize a solid color texture as follows: glCreateTextures(GL_TEXTURE_2D, 1, &_textureHandle); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glPixelStorei(GL_UNPACK_ROW_LENGTH, 0); // This doesn't change the outcome std::vector<unsigned char> data(3 * WIDTH * HEIGHT, static_cast<unsigned char>(200)); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, WIDTH, HEIGHT, 0, GL_RGB, GL_UNSIGNED_BYTE, data.data()); I then use the texture in Dear ImGUI like this: ImGui::Image((void*)(intptr_t) _textureHandle, ImVec2(WIDTH, HEIGHT)); However, this simply shows a black texture. I also tried a different way of initialization (to no avail): unsigned char* data = new unsigned char[3 * WIDTH * HEIGHT]; for (unsigned int i = 0; i < (int)(WIDTH * HEIGHT); i++) { data[i * 3] = (unsigned char)255; data[i * 3 + 1] = (unsigned char)50; data[i * 3 + 2] = (unsigned char)170; } glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, WIDTH, HEIGHT, 0, GL_RGB, GL_UNSIGNED_BYTE, data); Does anyone know what I'm doing wrong?
You created the texture by OpenGL 4.5 DSA, but didn't use DSA to set the texture parameters and image. You have to use glTextureParameter, glTextureStorage2D and glTextureSubImage2D instead of glTexParameter and glTexImage2D. glCreateTextures(GL_TEXTURE_2D, 1, &_textureHandle); glTextureParameteri(_textureHandle, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTextureParameteri(_textureHandle, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTextureParameteri(_textureHandle, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTextureParameteri(_textureHandle, GL_TEXTURE_MAG_FILTER, GL_LINEAR); std::vector<unsigned char> data(3 * WIDTH * HEIGHT, static_cast<unsigned char>(200)); glTextureStorage2D(_textureHandle, 1, GL_RGB8, WIDTH, HEIGHT); glTextureSubImage2D(_textureHandle, 0, 0, 0, WIDTH, HEIGHT, GL_RGB, GL_UNSIGNED_BYTE, data.data());
72,208,195
72,208,560
Dump a binary exe to hexadecimal and embed it into c++ file leads to execution error
I am dumping a sample of relec malware to hexadecimal using xxd to embed it in a c++ file and execute it with createprocess. When I get the hexadecimal relec file I copy it to an array and write it to disk. I call createprocess to execute the relec executable but I get the following error message: "The program can´t be run because it is incompatible with 64-bits Windows Versions...". Maybe the problem is that using xxd modify the content of the malware. I have also tried online conversors and it fails showing the same message. If the original exe is called with createprocess it work but I need it to be embedded. I use Linux to use xxd and use the resulting dump in windows 10. The IDE I am using is visual studio community 2019. Here is the code: unsigned char relec[] = { 0x4d, 0x5a, 0x90, 0x00, 0x03, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0xb8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00... void main(){ FILE* f = fopen("relec", "w"); fwrite(relec, sizeof(relec), 1, f); fclose(f); STARTUPINFOA si; PROCESS_INFORMATION pi; ZeroMemory(&si, sizeof(si)); si.cb = sizeof(si); ZeroMemory(&pi, sizeof(pi)); if (!CreateProcessA("relec", // No module name (use command line) NULL, // Command line NULL, // Process handle not inheritable NULL, // Thread handle not inheritable FALSE, // Set handle inheritance to FALSE 0, // No creation flags NULL, // Use parent's environment block NULL, // Use parent's starting directory &si, // Pointer to STARTUPINFO structure &pi) // Pointer to PROCESS_INFORMATION structure ) { printf("CreateProcess failed (%d).\n", GetLastError()); return; } }
I changed the fopen writing mode. Instead I used the write binary mode as @TedLyngmo suggested. Thank u all for your answers.
72,208,471
72,219,101
Set wallpaper from resource image file
I would like to set the background wallpaper from a resource image. I found and tried this code, but FindResource() can't find anything. Can anybody help me please? HINSTANCE hInstance = GetModuleHandle(NULL); std::cout << hInstance << std::endl; HRSRC hResInfo = FindResource(hInstance, MAKEINTRESOURCE(IDB_PNG1), RT_BITMAP); std::cout << hResInfo<< std::endl; HGLOBAL hRes = LoadResource(hInstance, hResInfo); std::cout << hRes << std::endl; LPVOID memRes = LockResource(hResInfo); DWORD sizeRes = SizeofResource(hInstance, hResInfo); std::cout << memRes<< std::endl; std::cout << sizeRes<< std::endl; HANDLE hFile = CreateFile("C:\\Users\\Asus\\Desktop\\test.png", GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); DWORD dwWritten = 0; WriteFile(hFile, memRes, sizeRes, &dwWritten, NULL); CloseHandle(hFile); SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, (PVOID) "C:\\Users\\Asus\\Desktop\\test.png", SPIF_UPDATEINIFILE); resource file #include "resource.h" IDI_ICON1 ICON "chrome.ico" IDB_PNG1 PNG "C:\\Users\\Asus\\Pictures\\jano.png" resource.h #define IDI_ICON1 101 #define IDB_PNG1 102
There are two mistakes in your code: You are creating the IDB_PNG1 resource as type PNG, but you are asking FindResource() to find a resource whose type is BITMAP instead. The types need to match, so replace RT_BITMAP with TEXT("PNG") in the call to FindResource(). Alternatively, use RCDATA instead of PNG in the .rc file, and then use RT_RCDATA instead of RT_BITMAP/"PNG" in the call to FindResource(). you are passing the wrong handle to LockResource(). You are passing in hResInfo that is returned by FindResource(), but you need to instead pass in hRes that is returned by LoadResource().
72,208,512
72,255,890
How to stop long operation on QThread?
I've made some research but I couldn't find the answer to why my solution is not working. But to the point. I've got QWidget as a separate dialog in my app. I'm using this QWidget class to gather paths to files and zip them into one file with ZipLib. To give users some feedback about the progress of the zipping I've added QProgressBar which is updated during zipping. But I've found out that in some cases when files are too big, zipping files are taking very long and makes my app not respond during this time. So my idea was to move the long operation of zipping to another thread using QThread and everything is working fine, zipping is working, and the progress bar is updated BUT there is a problem when I want to cancel the zipping operation. With my current approach action with zipping just don't listen to any of my requests to interrupt the thread and the thread is doing zipping even after I've closed my dialog. I'll show you my approach maybe there is something very trivial but I just can't make to cancel this zipping operation. tl;dr version: I can't interrupt QThread with requestInterruption() or any other way. This is my WorkerThread class: class WorkerThread : public QThread { Q_OBJECT public: void setup(std::string zip, std::vector<std::string> file) { mZip = zip; mFiles = file; mActionStopped = false; } void run() override { size_t progressValue = (100 / mFiles.size()); try { for (const auto& file : mFiles) { if (not isInterruptionRequested()) { Q_EMIT updateTheProgress(progressValue); ZipFile::AddFile(mZip, file); } else { return; } } } catch(const std::exception& e) { Q_EMIT resultReady(false); } if (not mActionStopped) { Q_EMIT updateTheProgress(100 - actualProgress); // To set 100% Q_EMIT resultReady(true); } } std::string mZip; std::vector<std::string> mFiles; size_t actualProgress = 0; bool mActionStopped; Q_SIGNALS: void resultReady(bool dupa); void updateProgress(int value); public Q_SLOTS: void updateTheProgress(int value) { actualProgress += value; Q_EMIT updateProgress(actualProgress); } void stopWork() { mActionStopped = true; } }; And in my QWidget class I've got something like this: workerThread = new WorkerThread(); connect(workerThread, &WorkerThread::resultReady, this, &ZipProjectDialog::zipDone); connect(workerThread, SIGNAL(updateProgress(int)), progressBar, SLOT(setValue(int))); connect(btnBox, &QDialogButtonBox::rejected, workerThread, &WorkerThread::requestInterruption); connect(btnBox, &QDialogButtonBox::rejected, workerThread, &WorkerThread::stopWork); workerThread->setup(zipFilename, filePathList); workerThread->start(); connect(workerThread, &WorkerThread::finished, workerThread, &QObject::deleteLater); I've followed QThread documentation with this but requestInterruption() is still not working. If someone has any idea how to resolve this I'll appreciate it. Thanks!
You cannot interrupt the execution of ZipFile::AddFile(mZip, file); itself. It is a single call to a function, and no one checks isInterruptionRequested() inside that function. A simplified example #include <QCoreApplication> #include <QDebug> #include <QThread> #include <QTimer> class MyThread : public QThread { public: void run() override { qDebug() << "starting"; for (int i = 0; i < 10; ++i) { qDebug() << "loop" << i; if (!isInterruptionRequested()) sleep(5); else break; } qDebug() << "finished"; } }; int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); MyThread thread; QTimer::singleShot(0, &thread, [&thread] { thread.start(); QTimer::singleShot(7000 /*7 seconds*/, &thread, [&thread] { qDebug() << "interrupting"; thread.requestInterruption(); }); }); return a.exec(); } prints starting loop 0 loop 1 interrupting loop 2 finished as expected. And as expected there are a few seconds delay between "interrupting" and "loop 2", and no delay between "loop 2" and "finished". If you want to interrupt your task more granular, then you have to find a more granular API than ZipFile::AddFile, so you can check isInterruptionRequested() regularly even while a single file is archived, or use an external process that can be killed instead.
72,208,838
72,209,648
Pass matrix of unknown dimensions to C++ function
The following code compiles with gcc but not g++. Is it possible to write a function with a matrix argument of arbitrary dimensions in C++? void print_mat(const int nr, const int nc, const float x[nr][nc]); #include <stdio.h> void print_mat(const int nr, const int nc, const float x[nr][nc]) { for (int ir=0; ir<nr; ir++) { for (int ic=0; ic<nc; ic++) { printf(" %f",x[ir][ic]); } printf("\n"); } }
To build on Peter’s answer, you can use the single-dimension variant with proper indexing to do the work. But you can make invoking the function much nicer in C++: void print_mat(const int nr, const int nc, const float *x) { ... } template <std::size_t NumRows, std::size_t NumColumns> void print_mat(const float (*x)[NumRows][NumColumns]) { print_mat((int)NumRows, (int)NumColumns, (const float *)x); } Now you can use the function naturally: float matrix[4][3] = { ... }; print_mat( matrix ); This only works, however, as long as you do not let the array downgrade to a pointer. Also, there are limit issues with the cast from size_t to int, but it really shouldn’t be possible to make one big enough that it would matter. EDIT: There are also potential buffering/alignment issues when casting a multidimensional array to a one-dimensional, flat array. But no common, modern compiler + hardware that I am aware of where this is an issue. Just be sure to know your target platform.
72,209,091
72,214,594
How to, given UV on a triangle, find XYZ?
I have a triangle, each point of which is defined by a position (X,Y,Z) and a UV coordinate (U,V): struct Vertex { Vector mPos; Point mUV; inline Vector& ToVector() {return mPos;} inline Vector& ToUV() {return mUV;} }; With this function, I am able to get the UV coordinate at a specific XYZ position: Point Math3D::TriangleXYZToUV(Vector thePos, Vertex* theTriangle) { Vector aTr1=theTriangle->ToVector()-(theTriangle+1)->ToVector(); Vector aTr2=theTriangle->ToVector()-(theTriangle+2)->ToVector(); Vector aF1 = theTriangle->ToVector()-thePos; Vector aF2 = (theTriangle+1)->ToVector()-thePos; Vector aF3 = (theTriangle+2)->ToVector()-thePos; float aA=aTr1.Cross(aTr2).Length(); float aA1=aF2.Cross(aF3).Length()/aA; float aA2=aF3.Cross(aF1).Length()/aA; float aA3=aF1.Cross(aF2).Length()/aA; Point aUV=(theTriangle->ToUV()*aA1)+((theTriangle+1)->ToUV()*aA2)+((theTriangle+2)->ToUV()*aA3); return aUV; } I attempted to reverse-engineer this to make a function that gets the XYZ coordinate from a specific UV position: Vector Math3D::TriangleUVToXYZ(Point theUV, Vertex* theTriangle) { Point aTr1=theTriangle->ToUV()-(theTriangle+1)->ToUV(); Point aTr2=theTriangle->ToUV()-(theTriangle+2)->ToUV(); Point aF1 = theTriangle->ToUV()-theUV; Point aF2 = (theTriangle+1)->ToUV()-theUV; Point aF3 = (theTriangle+2)->ToUV()-theUV; float aA=gMath.Abs(aTr1.Cross(aTr2)); // NOTE: Point::Cross looks like this: const float Cross(const Point &thePoint) const {return mX*thePoint.mY-mY*thePoint.mX;} float aA1=aF2.Cross(aF3)/aA; float aA2=aF3.Cross(aF1)/aA; float aA3=aF1.Cross(aF2)/aA; Vector aXYZ=(theTriangle->ToVector()*aA1)+((theTriangle+1)->ToVector()*aA2)+((theTriangle+2)->ToVector()*aA3); return aXYZ; } This works MOST of the time. However, it seems to exponentially "approach" the right-angled corner of the triangle-- or something. I'm not really sure what's going on except that the result gets wildly inaccurate the closer it gets to the right-angle. What do I need to do to this TriangleUVtoXYZ function to make it return accurate results?
I haven't tested your implementation, but you only need to compute two parametric coordinates - the third being redundant since they should sum to 1. Vector Math3D::TriangleUVToXYZ(Point theUV, Vertex* theTriangle) { // T2-T1, T3-T1, P-T1 Point aTr12 = theTriangle[1].ToUV() - theTriangle[0].ToUV(); Point aTr13 = theTriangle[2].ToUV() - theTriangle[0].ToUV(); Point aP1 = theUV - theTriangle[0].ToUV(); // don't need Abs() for the denominator float aA23 = aTr12.Cross(aTr13); // parametric coordinates [s,t] // s = (P-T1)x(T2-T1) / (T3-T1)x(T2-T1) // t = (P-T1)x(T3-T1) / (T2-T1)x(T3-T1) float aA12 = aP1.Cross(aTr12) / -aA23; float aA13 = aP1.Cross(aTr13) / aA23; // XYZ = V1 + s(V2-V1) + t(V3-V1) return theTriangle[0].ToVector() + aA12 * (theTriangle[1].ToVector() - theTriangle[0].ToVector()) + aA13 * (theTriangle[2].ToVector() - theTriangle[0].ToVector()); }
72,210,101
72,210,510
Copy constructor is called although I have provided the move constructor
I have implemented both copy constructor and move constructor and what i learned was the program must use Move constructor instead of copy constructor . class Move { private: int *data; // raw pointer public: Move(int); // constructor Move(const Move &source); // copy constructor Move(Move &&source); // Move Constructor ~Move(); }; Move::Move(int d) { data = new int; *data = d; cout << "Constructor for: " << d << endl; } Move::Move(const Move &source) : Move(*source.data) { cout << "Copy constructor -deep copy for: " << *data << endl; } Move::Move(Move &&source) : data{source.data} { source.data = nullptr; cout << "Move constructor -Moving resource: " << *data << endl; } Move::~Move() { if (data != nullptr) { cout << "Destructor freeing data for : " << *data << endl; } else { cout << "Destructor freeing data for nullptr" << endl; } delete data; } //driving function int main() { vector<Move> vec; vec.push_back(Move{10}); vec.push_back(Move{20}); vec.push_back(Move{30}); vec.push_back(Move{40}); vec.push_back(Move{50}); vec.push_back(Move{60}); vec.push_back(Move{70}); return 0; } Output: Constructor for: 10 Move constructor -Moving resource: 10 Destructor freeing data for nullptr Constructor for: 20 Move constructor -Moving resource: 20 Constructor for: 10 Copy constructor -deep copy for: 10 Destructor freeing data for : 10 Destructor freeing data for nullptr Constructor for: 30 Move constructor -Moving resource: 30 Constructor for: 10 Copy constructor -deep copy for: 10 Constructor for: 20 Copy constructor -deep copy for: 20 Destructor freeing data for : 10 Destructor freeing data for : 20 Destructor freeing data for nullptr Constructor for: 40 Move constructor -Moving resource: 40 Destructor freeing data for nullptr Constructor for: 50 Move constructor -Moving resource: 50 Constructor for: 10 Copy constructor -deep copy for: 10 Constructor for: 20 Copy constructor -deep copy for: 20 Constructor for: 30 Copy constructor -deep copy for: 30 Constructor for: 40 Copy constructor -deep copy for: 40 Destructor freeing data for : 10 Destructor freeing data for : 20 Destructor freeing data for : 30 Destructor freeing data for : 40 Destructor freeing data for nullptr Constructor for: 60 Move constructor -Moving resource: 60 Destructor freeing data for nullptr Constructor for: 70 Move constructor -Moving resource: 70 Destructor freeing data for nullptr Destructor freeing data for : 10 Destructor freeing data for : 20 Destructor freeing data for : 30 Destructor freeing data for : 40 Destructor freeing data for : 50 Destructor freeing data for : 60 Destructor freeing data for : 70
Because std::vector moves while resizing only if you have a noexcept move constructor. Or you can call vec.reserve(7) to avoid resizing.
72,210,210
72,261,716
Microsoft Key Storage Provider get keys
I am trying to get the details of keys in Microsoft Key Storage Provider. For this I open the storage provider using the below API call: NCryptOpenStorageProvider(&prov, MS_KEY_STORAGE_PROVIDER, 0); Then I call NCryptEnumKeys in a while loop to get the key details. However I am only able to get one key from the KSP. During the second iteration of the loop NCryptEnumKeys returns NTE_NO_MORE_ITEMS. But I have at-least 3 certificates in my local machine store that have Microsoft Key Storage Provider as Provider. I have confirmed the same through certutil -store my command. What could possibly be wrong?
After days of analysis and discussions, finally I was able to identify the root cause. It is related to privileges. If I run with Admin privilege, I can extract keys for ECDSA certificate as well from the Local Machine certificate store. If you do not intend to use Admin privilege, just take the certificate manager or mmc and select the certificate, take All tasks > Manage Private Keys give privileges as required.
72,210,455
72,212,742
Why are the results of the optimization on aliasing different for char* and std::string&?
void f1(int* count, char* str) { for (int i = 0; i < *count; ++i) str[i] = 0; } void f2(int* count, char8_t* str) { for (int i = 0; i < *count; ++i) str[i] = 0; } void f3(int* count, char* str) { int n = *count; for (int i = 0; i < n; ++i) str[i] = 0; } void f4(int* __restrict__ count, char* str) { // GCC extension; clang also supports it for (int i = 0; i < *count; ++i) str[i] = 0; } According to this article, the compiler (almost) replaces f2() with a call to memset(), however, the compiler generates machine code from f1() that is almost identical to the above code. Because the compiler can assume that count and str do not point to the same int object (strict aliasing rule) in f2(), but cannot make such an assumption in f1() (C++ allow aliasing any pointer type with a char*). Such aliasing problems can be avoided by dereferencing count in advance, as in f3(), or by using __restrict__, as in f4(). https://godbolt.org/z/fKTjcnW5f The following functions are std::string/std::u8string version of the above functions: void f5(int* count, std::string& str) { for (int i = 0; i < *count; ++i) str[i] = 0; } void f6(int* count, std::u8string& str) { for (int i = 0; i < *count; ++i) str[i] = 0; } void f7(int* count, std::string& str) { int n = *count; for (int i = 0; i < n; ++i) str[i] = 0; } void f8(int* __restrict__ count, std::string& str) { for (int i = 0; i < *count; ++i) str[i] = 0; } void f9(int* __restrict__ count, std::string& __restrict__ str) { for (int i = 0; i < *count; ++i) str[i] = 0; } https://godbolt.org/z/nsPdfhzoj My questions are: f5() and f6() are the same result as f1() and f2(), respectively. However, f7() and f8() do not have the same result as f3() and f4() (memset() was not used). Why? The compiler replaces f9() with a call to memset() (that does not happen with f8()). Why? Tested with GCC 12.1 on x86_64, -std=c++20 -O3.
I created a simplified demo for the string case: class String { char* data_; public: char& operator[](size_t i) { return data_[i]; } }; void f(int n, String& s) { for (int i = 0; i < n; i++) s[i] = 0; } The problem here is that the compiler cannot know whether writing to data_[i] does not change the value of data_. With the restricted s parameter, you tell the compiler that this cannot happen. Live demo: https://godbolt.org/z/jjn9d3Mxe This is not necessary for passing a pointer, since it is passed in the register, so it cannot be aliased with the pointed-to data. However, if this pointer is a global variable, the same problem occurs. Live demo: https://godbolt.org/z/Y3nWvn6rW
72,210,655
72,211,816
visual C++ and u8 prefix
I was writting a HTTP server in visual studio preview, and I add <meta charset="utf-8"> to use UTF-8 as content encoding. The problem is when I use u8 prefix on string literal, the browser looks like has encoding error. when I remove u8 prefix, the browser show correctly. Why? and my document was save with utf-8 (code page 65001) string with u8 prefix string without u8 prefix EDIT update example code #define WIN32_LEAN_AND_MEAN #include <Windows.h> #include <winsock2.h> #include <ws2tcpip.h> #include <stdio.h> #pragma comment (lib, "ws2_32.lib") #define U8 #ifdef U8 typedef const char8_t c; c str[] = u8"HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=utf-8\r\n\r\n<h1>\xf0\x9f\x93\x9d</h1>"; #else typedef const char c; c str[] = "HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=utf-8\r\n\r\n<h1>\xf0\x9f\x93\x9d</h1>"; #endif template <ULONG N> constexpr ULONG cstrlen(c(&)[N]) { return N - 1; } int main() { WSADATA wsaData; SOCKET listener, s; CHAR buf[1024 * 3]; WSABUF wsabuf{ .len = sizeof(buf), .buf = buf }; DWORD bytes, flags = 0; const char* err = "?"; if (WSAStartup(MAKEWORD(2, 2), &wsaData)) { err = "WSAStartup"; goto Err; } { struct addrinfo hints = {}; hints.ai_family = AF_INET; hints.ai_socktype = SOCK_STREAM; hints.ai_protocol = IPPROTO_TCP; hints.ai_flags = AI_PASSIVE; struct addrinfo* result; if (getaddrinfo(NULL, "80", &hints, &result)) { err = "getaddrinfo"; goto Err; } listener = WSASocket(AF_INET, SOCK_STREAM, IPPROTO_IP, NULL, 0, WSA_FLAG_OVERLAPPED | WSA_FLAG_NO_HANDLE_INHERIT); if (listener == INVALID_SOCKET) { freeaddrinfo(result); err = "WSASocket"; goto Err; } if (bind(listener, result->ai_addr, (int)result->ai_addrlen) == SOCKET_ERROR) { freeaddrinfo(result); err = "bind"; closesocket(listener); goto Err; } freeaddrinfo(result); if (listen(listener, SOMAXCONN) == SOCKET_ERROR) { err = "listen"; closesocket(listener); goto Err; } } puts("Ready..."); for (;;) { s = WSAAccept(listener, NULL, NULL, NULL, NULL); if (s == INVALID_SOCKET) { closesocket(listener); err = "WSAAccept"; goto Err; } wsabuf.len = sizeof(buf); wsabuf.buf = buf; bytes = flags = 0; if (WSARecv(s, &wsabuf, 1, &bytes, &flags, NULL, NULL) == SOCKET_ERROR) { err = "WSARecv"; goto Err; } wsabuf.buf = (char*)str; wsabuf.len = cstrlen(str); if (WSASend(s, &wsabuf, 1, &bytes, 0, NULL, NULL)) { err = "WSASend"; closesocket(s); goto Err; } closesocket(s); } return 0; Err: puts(err); WSACleanup(); return 1; } run with std=c++20
thanks to @AlanBirtles, use \u literal solve my problem. u8 and no u8 both works in \U0001f4dd update code #define WIN32_LEAN_AND_MEAN #include <Windows.h> #include <winsock2.h> #include <ws2tcpip.h> #include <stdio.h> #pragma comment (lib, "ws2_32.lib") #define U8 #ifdef U8 typedef const char8_t c; c str[] = u8"HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=utf-8\r\n\r\n<h1>\U0001f4dd</h1>"; #else typedef const char c; c str[] = "HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=utf-8\r\n\r\n<h1>\U0001f4dd</h1>"; #endif const char c; template <ULONG N> constexpr ULONG cstrlen(c(&)[N]) { return N - 1; } int main() { WSADATA wsaData; SOCKET listener, s; CHAR buf[1024 * 3]; WSABUF wsabuf{ .len = sizeof(buf), .buf = buf }; DWORD bytes, flags = 0; const char* err = "?"; if (WSAStartup(MAKEWORD(2, 2), &wsaData)) { err = "WSAStartup"; goto Err; } { struct addrinfo hints = {}; hints.ai_family = AF_INET; hints.ai_socktype = SOCK_STREAM; hints.ai_protocol = IPPROTO_TCP; hints.ai_flags = AI_PASSIVE; struct addrinfo* result; if (getaddrinfo(NULL, "80", &hints, &result)) { err = "getaddrinfo"; goto Err; } listener = WSASocket(AF_INET, SOCK_STREAM, IPPROTO_IP, NULL, 0, WSA_FLAG_OVERLAPPED | WSA_FLAG_NO_HANDLE_INHERIT); if (listener == INVALID_SOCKET) { freeaddrinfo(result); err = "WSASocket"; goto Err; } if (bind(listener, result->ai_addr, (int)result->ai_addrlen) == SOCKET_ERROR) { freeaddrinfo(result); err = "bind"; closesocket(listener); goto Err; } freeaddrinfo(result); if (listen(listener, SOMAXCONN) == SOCKET_ERROR) { err = "listen"; closesocket(listener); goto Err; } } puts("Ready..."); for (;;) { s = WSAAccept(listener, NULL, NULL, NULL, NULL); if (s == INVALID_SOCKET) { closesocket(listener); err = "WSAAccept"; goto Err; } wsabuf.len = sizeof(buf); wsabuf.buf = buf; bytes = flags = 0; if (WSARecv(s, &wsabuf, 1, &bytes, &flags, NULL, NULL) == SOCKET_ERROR) { err = "WSARecv"; goto Err; } wsabuf.buf = (char*)str; wsabuf.len = cstrlen(str); if (WSASend(s, &wsabuf, 1, &bytes, 0, NULL, NULL)) { err = "WSASend"; closesocket(s); goto Err; } closesocket(s); } return 0; Err: puts(err); WSACleanup(); return 1; }
72,211,047
72,217,459
How to include library from sibling directory in CMakeLists.txt for compilation
I am working on a C project as of recently and want to learn how to use CMake properly. The project consists of the following directory structure (as of now): . └── system ├── collections │ ├── bin │ ├── build │ ├── includes │ └── src └── private └── corelib ├── bin ├── build ├── includes └── src Every directory including 'bin' sub-directories is a separate library. They contain a CMakeLists.txt each. The plan is to link the libraries in such a way that, during development, no manual recompilation of 'corelib' should be required to receive updated code from it, while also ensuring that dependencies would be resolved once all libraries get compiled as SHARED libraries and put in a place such as 'usr/local/lib' or similar. I have a dependency of library 'corelib' in library 'collections'. Trying to resolve said dependency, I have come up with the following CMakeLists.txt in 'collections': cmake_minimum_required(VERSION 3.0.0) project(collections VERSION 0.1.0 LANGUAGES C) set(LIBRARY_OUTPUT_PATH ../bin) add_subdirectory(../private/corelib ${LIBRARY_OUTPUT_PATH}) include_directories(./includes) aux_source_directory(./src SOURCES) add_library(collections SHARED ${SOURCES} main.c) However, this does not produce the result I am looking for, as I get the following output on build: [main] Building folder: collections [build] Starting build [proc] Executing command: /usr/bin/cmake --build /home/codeuntu/Repositories/netcore-c/src/system/collections/build --config Debug --target all -j 6 -- [build] gmake[1]: *** No rule to make target '../bin/all', needed by 'all'. Stop. [build] gmake[1]: *** Waiting for unfinished jobs.... [build] Consolidate compiler generated dependencies of target collections [build] [ 50%] Built target collections [build] gmake: *** [Makefile:91: all] Error 2 [build] Build finished with exit code 2 It seems this is the wrong way to go about it. Any help is greatly appreciated. This is the CMakeLists.txt for 'corelib': cmake_minimum_required(VERSION 3.0.0) project(corelib VERSION 0.1.0 LANGUAGES C) include_directories(./includes) aux_source_directory(./src SOURCES) set(LIBRARY_OUTPUT_PATH ../bin) add_library(corelib SHARED ${SOURCES} main.c)
Binary directory has to be a subdirectory of current dir, it can't be above ../bin. Use: add_subdirectory(../private/corelib some_unique_name) Overall, let's fix some issues. A more advanced CMake might look like this: # system/CmakeLists.txt add_subdirectory(private EXCLUDE_FROM_ALL) add_subdirectory(collections) # system/collections/CMakeLists.txt cmake_minimum_required(VERSION 3.11) project(collections VERSION 0.1.0 LANGUAGES C) file(GLOB_RECURSE srcs *.c *.h) add_library(collections ${srcs}) # Use only target_* intefaces target_include_directories(collections PUBLIC ./includes ) target_link_libraries(collections PRIVATE corelib ) # system/private/CMakeLists.txt add_subdirectory(corelib) # system/private/corelib/CMakeLists.txt cmake_minimum_required(VERSION 3.11) project(corelib VERSION 0.1.0 LANGUAGES C) file(GLOB_RECURSE srcs *.c *.h) add_library(corelib ${srcs}) target_include_directorieS(corelib PUBLIC ./includes) # system/CMakePresets.json { ... see documentation ... "configurePresets": [ { ... "cacheVariables": { "BUILD_SHARED_LIBS": "1", "ARCHIVE_OUTPUT_DIRECTORY": "${binaryDir}/bin", "LIBRARY_OUTPUT_DIRECTORY": "${binaryDir}/bin", "RUNTIME_OUTPUT_DIRECTORY": "${binaryDir}/bin" } } I.e. overall, I do not think every project inside system wants to compile his own separate instance of corelib, rather one corelib should be shared. Just add corelib once, from anywhere. Note that it doesn't have to be in order - you can target_link_libraries on targets before they are defined.
72,211,074
72,211,197
Having trouble including header files
I can only use header files that I add to C:\SDL2-w64\include, but I Can't get it to link to the include folder inside my project folder. for example: I have a folder called "MyProject" and its located at C:\Users\User\Desktop\MyProject, inside the project folder there is an "Include" folder located at \MyProject\Include then I add a header file called "head.h" to the Include path. in my code I use #include <head.h>, I then get the error cannot open source file "head.h", but if I add head.h to C:\SDL2-w64\include it works perfectly fine. anyone know how to include the Include folder located in my project folder?
Assuming the file doing the including is located at C:\Users\User\Desktop\MyProject, try using #include "Include/head.h". This is because there is a difference between using quotations ("") and angle brackets (<>) in your includes. The reason is explained in this answer: https://stackoverflow.com/a/3162067/19099501 But to summarize it, with most compilers, #include "blah.h" will search in the local directory first, and then the stuff it can reach from what's in your PATH variable, and #include <blah.h> will search from what's in PATH only. I am guessing that C:\SDL2-w64\include is in your PATH. That is probably why when you moved the header file to that location, it was able to find it.
72,211,174
72,212,255
declare a template vector member in a class without template the class?
I have some class that should be populated with values, but I don't know the type of values. To clarify, each vector in a class instance is populated with the same value types, But one instance of SomeClass can have vector<int> and another vector<string> and so on. How can I declare the vector as template, but not template the class itself? template<typename T> struct tvector { typedef std::vector< std::vector<T> > type; }; class SomeClass { public: int _someField; tvector<T> _fieldValues; // this line fails to compile }; Thanks in advance
There are a few different ways to shear this beast. It mostly depends on how you want to access this vector and how you determine its exact type at runtime. std::variant A variant can store a set of predetermined types. It's effective but also cumbersome if you have many different types because you have to funnel every access through some type checking. class SomeClass { public: using variant_type = std::variant< std::vector<int>, std::vector<double> >; int _someField; variant_type _fieldValues; void print(std::ostream& stream) const { switch(_fieldValues.index()) { case 0: for(int i: std::get<0>(_fieldValues)) stream << i << ' '; break; case 1: for(double i: std::get<1>(_fieldValues)) stream << i << ' '; break; default: break; } } }; std::any Any can hold literally any type. Improves extendability but makes working with the values hard. class SomeClass { public: int _someField; std::any _fieldValues; void print(std::ostream& stream) const { if(_fieldValues.type() == typeid(std::vector<int>)) for(int i: std::any_cast<std::vector<int>>(_fieldValues)) stream << i << ' '; else if(_fieldValues.type() == typeid(std::vector<double>)) for(double i: std::any_cast<std::vector<double>>(_fieldValues)) stream << i << ' '; else throw std::runtime_error("Not implemented"); } }; Subclassing The most elegant way (IMHO) is to use a templated subclass. Something like this: class SomeClass { public: int _someField; virtual ~SomeClass() = default; virtual void print(std::ostream& stream) const = 0; }; template<class T> SomeClassT: public SomeClass { std::vector<T> _fieldValues; public: virtual void print(std::ostream& stream) const { for(const T& i: _fieldValues) stream << i << ' '; } }; Or if you don't want to expose that part, make it a private member. class SomeClassHelper { public: virtual ~SomeClassHelper() = default; virtual void print(std::ostream& stream) const = 0; }; template<class T> SomeClassHelperT: public SomeClassHelper { std::vector<T> _fieldValues; public: virtual void print(std::ostream& stream) const { for(const T& i: _fieldValues) stream << i << ' '; } }; class SomeClass { public: int _someField; private: std::unique_ptr<SomeClassHelper> helper; public: void print(std::ostream& stream) const { return helper->print(stream); } };
72,211,630
72,405,147
Forward Declaration of Constrained Template Specializations
I've been doing constrained partial class template specializations using C++20 concepts for a while now and they work great, but I and ran into a problem when attempting to forward declare them: godbolt example #include <concepts> template <class T> concept Integer = std::is_same_v<T,int> || std::is_same_v<T,unsigned int>; template <class T> concept Float = std::is_same_v<T,float> || std::is_same_v<T,double>; template <class T> class S {}; template <Integer T> class S<T>; // This forward declaration breaks GCC template <Float T> class S<T>; template <Integer T> class S<T> {}; template <Float T> class S<T> {}; int main() { S<int> s_int; S<float> s_float; } The second forward declaration // This forward declaration breaks GCC template <Float T> class S<T>; breaks GCC, but Clang and MSVC have no issues with it. I've had very similar problems with concepts in the past (which still haven't been fixed yet) but it was the other way around: GCC was conformant yet Clang and MSVC incorrectly rejected the code. Ditching concepts and explicitly specializing for int and float is accepted by GCC as well (godbolt example). Any ideas what's going on here?
Was a bug; is now fixed. No idea which version this fix will make it into. https://gcc.gnu.org/bugzilla/show_bug.cgi?id=96363
72,212,385
72,212,633
why is copy constructor called twice in this code?
When I execute the below code, a copy constructor of AAA is called twice between boo and foo. I just wonder when each of them is called exactly. Code: #include <iostream> #include <vector> class AAA { public: AAA(void) { std::cout<<"AAA ctor"<<std::endl; } AAA(const AAA& aRhs) { std::cout<<"AAA copy ctor"<<std::endl; } AAA(AAA&& aRhs) = default; }; void foo(std::vector<AAA>&& aVec) { std::cout<<"----foo"<<std::endl; } void boo(const AAA& a) { std::cout<<"----boo"<<std::endl; foo({a}); std::cout<<"----boo"<<std::endl; } int main(void) { AAA a; boo(a); return 0; } Output: AAA ctor ----boo AAA copy ctor AAA copy ctor ----foo ----boo
The copy constructor is invoked twice here: foo({a}); First to construct the elements of the initializer list, and second to copy the values from the initializer list to the std::vector.
72,212,408
72,212,479
How to initialise and return an std::array within a template function?
I'd like a template function that returns some initialisation. I did the following: #include<iostream> #include<array> template <typename T> inline static constexpr T SetValues() { if(std::is_integral<T>::value) { std::cout<<"int\n"; return T{1}; } else { std::cout<<"array\n"; T arr = {1,2,3,4}; return arr; } } int main() { int a = 6; std::array<int, 4> arr = {2,2,2,2}; a = SetValues<decltype(a)>(); arr = SetValues<decltype(arr)>(); return 0; } which correctly initialises the int but in case of the array I get the error scalar object ‘arr’ requires one element in initializer How should I initialise and return the array?
The problem is that, when T = int, you're trying to trying to initialize int arr with initializer list {1, 2, 3, 4} in the else branch. Even if you don't execute the else branch, the compiler still has to compile it and int arr = {1, 2, 3, 4} is invalid syntax. On C++17 (and higher), you can get away with if constexpr: template <typename T> inline static constexpr T SetValues() { if constexpr (std::is_integral<T>::value) { std::cout << "int\n"; return T{1}; } else { std::cout << "array\n"; T arr = {1, 2, 3, 4}; return arr; } } With if constexpr, the compiler won't compile the else branch when T is an integral type (e.g. int) and will not compile the if branch when T is not an integral type.
72,212,409
72,227,863
Neatly linking dependency tuple references specified by variadic class args
Given the following class structure in which we possess a number of different classes C#, each with unique data that is passed into a number of ledgers L<C#>, as well as possessing a number of classes S#, each depending on some subset of the classes under the C#, I have established a tuple containing all ledgers in the manager class E. // Dependency classes struct C {}; struct C1 : C {}; struct C2 : C {}; // Dependency data ledger template <class T> class L {}; // Dependency user template <class... Cs> struct S { using Deps = std::tuple<Cs...>; using DepRefs = std::tuple<L<Cs>&...>; }; struct S1 : S<C1> {}; struct S2 : S<C1, C2> {}; // Manager template <class... Ss> class E; template <class... Ss> class E : public E<all_deps_no_duplicates<Ss...>, Ss...> {}; template <class... Cs, class... Ss> class E<std::tuple<Cs...>, Ss...> { std::tuple<L<Cs>...> DepsData; std::tuple<typename Ss::DepsRefs...> DepsRefs; // Problem instantiation. }; // Usage int main() { E<S1, S2> e; }; What elegant solutions exist then to establish a secondary tuple containing references to each one of each dependency user's dependency ledgers? There are no duplicates in the tuple of dependency ledgers with one ledger per dependency with perhaps many dependency users each. For example, in the code given, I would want the first and second tuples in the manager class E to respectively contain: DepsData: std::tuple< L<C1>(), // 1st element: a ledger for C1 L<C2>() // 2nd element: a ledger for C2 > DepsRefs: std::tuple< std::tuple<L<C1>&>, // tuple containing reference to DepsData 1st element std::tuple<L<C1>&, L<C2>&> // tuple containing reference to DepsData 1st and 2nd elements > With both L<C1>& references in DepsRefs referring to the same ledger specified in DepsData.
So focusing on the reference initialization, you might do something like: template <typename T> struct Tag{}; template <typename... Ts, typename Tuple> std::tuple<L<Ts>&...> make_ref_tuple(Tag<std::tuple<L<Ts>&...>>, Tuple& tuple) { return {std::get<L<Ts>>(tuple)...}; } template <class... Cs, class... Ss> class E<std::tuple<Cs...>, Ss...> { std::tuple<L<Cs>...> DepsData; std::tuple<typename Ss::DepsRefs...> DepsRefs = { make_ref_tuple(Tag<typename Ss::DepsRefs>{}, DepsData)... }; }; Demo
72,212,536
72,213,799
how to iterate through several vectors with DIFFERENT types?
Here, I have a custom collection of entities (vectors of different types: Type1, Type2, Type3 , Type4, for simplicity I reduced to two types) with different sizes: #include <stdio.h> #include <vector> template<typename DataType> struct AbstractEntity { public: virtual std::vector<DataType>& getParticlesCPU() = 0; virtual void print() {}; }; // there is one of // realization of AbstractEntity class template<typename DataType> class ClothEntity : public AbstractEntity<DataType> { public: ClothEntity(){ particles.push_back(DataType(1)); particles.push_back(DataType(2)); } virtual std::vector<DataType>& getParticlesCPU() override { return particles; } virtual void print(){ for (auto& a : particles) printf("%d\n", a.x); } private: std::vector<DataType> particles; }; struct Type1{ int x; Type1(int x_){x = x_;} }; struct Type2{ int x; float y; Type2(int x_){x = x_; y = 0;} }; class EntityCollection{ using Entity1 = AbstractEntity<Type1>; using Entity2 = AbstractEntity<Type2>; public: EntityCollection(){} void push_back(Entity1* entity){ entities1.push_back(entity); } void push_back(Entity2* entity){ entities2.push_back(entity); } std::vector<Entity1*> getEntity1(){ return entities1; } std::vector<Entity2*> getEntity2(){ return entities2; } private: template< typename... Ts > using custom_function_t = void (*) ( Ts... ); template<typename Entity, typename... Ts > double fun_per_entity( std::vector<Entity>& entities, custom_function_t<Ts...> f, Ts... args ) { for(auto& entity : entities){ f(entity, args...); } } public: template<typename... Ts > void run_function(custom_function_t<Ts...> f, Ts... args){ fun_per_entity(entities1, f, args...); fun_per_entity(entities2, f, args...); } private: std::vector<Entity1*> entities1; std::vector<Entity2*> entities2; }; int main() { EntityCollection ec; ClothEntity<Type1> e1; ClothEntity<Type2> e2; ec.push_back(&e1); ec.push_back(&e2); // ec.run_function(print); // does not work for (auto& ev: ec.getEntity1()) ev->print(); for (auto& ev: ec.getEntity2()) ev->print(); return 0; } My goal is safely iterate over all vectors (entities1, entities2, ...) to run a given external function f_external(Entity e, Args...): for (auto& e : entities1) f_external(e, args...) for (auto& e : entities2) f_external(e, args...) or internal function f_internal(Args...): for (auto& e : entities1) e->f_internal(args...) for (auto& e : entities2) e->f_internal(args...) Right now, I am writing a lot of code each time: EntityCollection ec; for (auto& e : ec.getEntity1()) e->f_internal(args...) for (auto& e : ec.getEntity2()) e->f_internal(args...) How to automate it in order to minimize the mistakes and changes with adding new Types? I would be grateful if you use C++17.
Make your run_function member function take a functor instead of a function pointer: template<typename Entity, typename F, typename... Ts> static void fun_per_entity(std::vector<Entity*>& entities, F&& f, Ts&&... args) { for (auto& entity : entities) { f(entity, args...); } } public: template<typename F, typename... Ts> void run_function(F&& f, Ts&&... args) { fun_per_entity(entities1, f, args...); fun_per_entity(entities2, f, args...); fun_per_entity(entities3, f, args...); // ... } And you can use it with a lambda: ec.run_function([&](auto* e) { f_external(e, args...); }); ec.run_function([&](auto* e) { e->f_internal(args...); }); Also consider making template<typename DataType> class AbstractEntity derive from some non-template base so you only need one vector
72,212,891
72,213,542
What's the difference between using an mt19937_64 instance with or without the function call operator ()?
I created an mt19937_64 instance with a seed like so; std::mt19937_64 mt_engine{9156} What's the difference between using the instance like: mt_engine() or just mt_engine in code. And when should I use either? I can't seem to find any material that explains this precisely. All I find on this stuff is either filled with unnecessary information I don't need or math I do not understand at the moment so be of help? Edit: I'd include code of the two instances #include <random> #include <iostream> int main() { std::mt19937_64 mt_engine{91586} std::cout << mt_engine(); // outputs just one long number std::cout << mt_engine; //outputs sort of like an array of long numbers } What's the difference between the two use cases? Thanks.
mt_engine is an expression of type std::mt19937_64. You use it to refer to the generator. mt_engine() is an expression of type std::uint_fast64_t. You use it when you want a random number from the generator. What's the difference between the two use cases? std::cout << mt_engine() generates a random number, and outputs the number. std::cout << mt_engine outputs the internal state of mt_engine See operator<<,>>(std::mersenne_twister_engine) Serializes the internal state of the pseudo-random number engine e as a sequence of decimal numbers separated by one or more spaces, and inserts it to the stream ost. The fill character and the formatting flags of the stream are ignored and unaffected.
72,213,072
72,220,727
Unable to refer to typedef struct definitions done in Win32 Header files (.h files in External dependencies) from WinRT C++ Library
Unable to refer to typedef struct definitions done in Win32 Header files (.h files in External dependencies) when consumed from WinRT C++ Library #include <mfplay.h> #pragma comment(lib,"Mfplay.lib") class MediaPlayerCallback //: public IMFPMediaPlayerCallback { long m_cRef; // Reference count MFP_EVENT_HEADER H; }; MFP_EVENT_HEADER is a typedef struct defined inside MFPlay.h, Doing a Go to the definition in VS2019 takes me to the definition in MFPlay.h definition but the code doesn't compile But I tried creating a typedef struct in a .h file I have created and I'm able to compile that without any issues. My doubt is why am I not able to compile when defined in MFPlay.h but able to compile when defined in header files defined by me. The error I'm getting MediaPlayerCallback.h(11,22): error C3646: 'H': unknown override specifier MediaPlayerCallback.h(11,23): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int Minimum Reproducible Already Tried- Tried the same code on the win32 desktop app and I'm able to compile without any issues but when doing the same thing from a WinRT C++ library getting this issue
As noted in the comments, the issue is that the MFP_EVENT_HEADER type is in the WINAPI_FAMILY_DESKTOP_APP API partition but is not in the WINAPI_FAMILY_APP API partition supported for UWP applications. Per Microsoft Docs this type is marked " [desktop apps only]". IMFPMediaPlayerCallback is also "desktop apps only". This is because this API is considered deprecated per Microsoft Docs. The recommendation is to use Media Session APIs instead although IMFMediaSession is also a desktop only interface. For UWP, the list of Media Foundation APIs supported is found here. There is also the Windows.Media Windows Runtime API surface. I recommend starting with Audio, video, and camera and see what is supported for your scenario.
72,213,782
72,213,858
Append to String a Signed Int (Converted to Bytes) in Big Endian
I have a 4 byte integer (signed), and (i) I want to reverse the byte order, (ii) I want to store the bytes (i.e. the 4 bytes) as bytes of the string. I am working in C++. In order to reverse the byte order in Big Endian, I was using the ntohl, but I cannot use that due the fact that my numbers can be also negative. Example: int32_t a = -123456; string s; s.append(reinterpret_cast<char*>(reinterpret_cast<void*>(&a))); // int to byte Further, when I am appending these data, it seems that I am appending 8 bytes instead of 4, why? I need to use the append (I cannot use memcpy or something else). Do you have any suggestion?
I was using the ntohl, but I cannot use that due the fact that my numbers can be also negative. It's unclear why you think that negative number would be a problem. It's fine to convert negative numbers with ntohl. s.append(reinterpret_cast<char*>(reinterpret_cast<void*>(&a))); std::string::append(char*) requires that the argument points to a null terminated string. An integer is not null terminated (unless it happens to contain a byte that incidentally represents a null terminator character). As a result of violating this requirement, the behaviour of the program is undefined. Do you have any suggestion? To fix this bug, you can use the std::string::append(char*, size_type) overload instead: s.append(reinterpret_cast<char*>(&a), sizeof a); reinterpret_cast<char*>(reinterpret_cast<void*> The inner cast to void* is redundant. It makes no difference.
72,213,987
72,214,145
How to use C++ std::barrier arrival_token?
I keep getting a compiler error when using the std::barrier arrive and wait functions separately. I've been trying to find examples of using these functions but I can't find them so I'm just shooting wild at this point. It complaines that my arrival token is not an rvalue, so I changed the declaration to use &&, but I'm not that familiar with how rvalues work. Here's the code: void thread_fn(std::barrier<>& sync_point) { /* Do 1st task... */ std::barrier<>::arrival_token&& arrival = sync_point.arrive(); /* Do 2nd task... */ /* Wait for everyone to finish 1st task */ sync_point.wait(arrival); /* Do 3rd task... */ } I get the compile error: test.cpp: In function ‘void thread_fn(std::barrier<>&)’: test.cpp:12:21: error: cannot bind rvalue reference of type ‘std::barrier<>::arrival_token&&’ to lvalue of type ‘std::barrier<>::arrival_token’ 12 | sync_point.wait(arrival); | ^~~~~~~
A variable with an rvalue reference type is an lvalue (arrival is an lvalue). std::barrier<>::wait takes an arrival_token&&, so you need to move from the lvalue: sync_point.wait(std::move(arrival));
72,214,059
72,214,759
Run time error assigning cv::Mat element value using cv::Mat::at
In the following code I would like to assign a values to elements of a Mat variable in a loop. I get the runtime error below. pair<Mat, Mat> meshgrid(vector<int> x, vector<int> y) { int sx = (int)x.size(); int sy = (int)y.size(); Mat xmat = Mat::ones(sy, sx, CV_16U); Mat ymat = Mat::ones(sy, sy, CV_16U); for (int i = 0; i < sx; i++) { for (int j = 0; j < sy; j++) { xmat.at<int>(i, j) = j; // <------- here is place of error. cout << j << "\t"; } cout << endl; } for (int i = 0; i < sx; i++) { for (int j = 0; j < sy; j++) { ymat.at<int>(i, j) = i; // <------- here is place of error. cout << j << "\t"; } cout << endl; } return make_pair(xmat, ymat); } This picture when debuging; This is the run time error I get: OpenCV(...) Error: Assertion failed (((((sizeof(size_t)<<28)|0x8442211) >> ((traits::Depth<_Tp>::value) & ((1 << 3) - 1))*4) & 15) == elemSize1()) in cv::Mat::at, file ...\include\opencv2\core\mat.inl.hpp, line 1108 Thank you for your answers.
I assume you meant to generate output similar to numpy.meshgrid, and Matlab meshgrid. There are several errors in your code: The cv::Mat is initialized with type CV_16U (i.e. 16 bit unsigned value), but when you access the elements with at you use int (which is 32bit signed). You should change it to at<unsigned short> (or change the type of the cv::Mat to 32 bit signed - CV_32S). You initialized the cv::Mat with wrong sizes: xmat has size of (sy, sx), but ymat has size of (sy, sy). The indices (row, col) you used to access the mat elements were incorrect. To make it easier to use correctly, I changed the names of the dimentions to rows, cols, and the loop indices to iRow, iCol. The values in the matrices should come from the values in x and y vectors (not the indices). See updated code below (and the notes following it regarding the changes): #include <opencv2/core/core.hpp> #include <vector> #include <iostream> std::pair<cv::Mat, cv::Mat> meshgrid(std::vector<unsigned short> const & x, std::vector<unsigned short> const & y) { int cols = static_cast<int>(x.size()); int rows = static_cast<int>(y.size()); cv::Mat xmat(rows, cols, CV_16U); cv::Mat ymat(rows, cols, CV_16U); for (int iRow = 0; iRow < rows; ++iRow) { auto * pRowData = xmat.ptr<unsigned short>(iRow); for (int iCol = 0; iCol < cols; ++iCol) { pRowData[iCol] = x[iCol]; std::cout << pRowData[iCol] << "\t"; } std::cout << std::endl; } std::cout << std::endl; for (int iRow = 0; iRow < rows; ++iRow) { auto * pRowData = ymat.ptr<unsigned short>(iRow); for (int iCol = 0; iCol < cols; ++iCol) { pRowData[iCol] = y[iRow]; std::cout << pRowData[iCol] << "\t"; } std::cout << std::endl; } return std::make_pair(std::move(xmat), std::move(ymat)); } int main() { std::vector<unsigned short> xxx{ 1,2 }; std::vector<unsigned short> yyy{ 10,11,12 }; auto p = meshgrid(xxx, yyy); return 0; } Output: 1 2 1 2 1 2 10 10 11 11 12 12 Some notes: I might have misunderstood which values you wanted to set in the cv::Mat's. But at least now you have code that does not crash. You can change the assigned values as you wish. Using at to access cv::Mat elements one after the other is very inefficient, because at contains some validations for every access. It's a lot more efficient to use the cv::Mat method ptr, that gives you a pointer to the data of a row. Then you can use this pointer to traverse the row more efficiently - see above In any method, it is more efficient to traverse a cv::Mat one row after another (and not column by column). This causes you to access continous memory, and decrease the number of cache misses. In your real code, it's better to separate calculations from I/O. Therefore it's better if your meshgrid function will only create the matrices. Print them outside if you need. No need to initialize the cv::Mats to ones, because immediatly afterwards we set the values for all elements. In my code x and y are passed to the function by const refernce. It is more efficient (avoid copy) and also forces the compiler to verify the vectors are not modified. Better to avoid using namespace std - see here Why is "using namespace std;" considered bad practice?. From similar reasons I recomend to avoid using namespace cv as well.
72,214,285
72,225,294
QT Creator and OpenCV455: 'arm_neon.h' file not found
I'm building a project using qt6 and opencv455. I'm doing this on the new MacBook with a silicon chip (arm64). I can compile the whole project without errors, but I always get the 'arm_neon.h' file not found error message in the editor and therefore the syntax highlighting and warning display doesn't work correctly for the rest of the code. I've added some more details below - any help appreciated. Stack: Qt Creator 7.0.1 Based on Qt 6.2.3 (Clang 13.0 (Apple), 64 bit) Self compiled OpenCv 455 version according to official docs Error: X.h: In included file: 'arm_neon.h' file not found cv_cpu_dispatch.h:219:12: error occurred here What I've tried: Re-installing everything, recompiling opencv, reinstalling the command line tools, updating the command line tools, double checked every link.
Okay, I found a solution after three days of re-installing and re-compiling everything in every possible configuration (like opencv with unix makefiles, xcode, forced target architecture of arm64 etc). What finally worked was to disable the ClangCodeModel flag in the plugin section of QtCreator (Menu: About/Plugins/ -> search for ClangCodeModel, disable the plugin and restart the application. I'm pretty sure this is just a workaround, but at least I can work now as it should be and maybe this helps someone else. If anyone has some input on how to fix this issue at its core, any help or alternative answer is very appreciated.
72,215,492
72,217,501
How to link shared library on linux using cmake?
How to link shared library on linux platform? I downloaded sfml library using apt cmd and I tried to run simple example: main.cpp #include <SFML/Graphics.hpp> int main() { // Make a window that is 800 by 200 pixels // And has the title "Hello from SFML" sf::RenderWindow window(sf::VideoMode(800, 200), "Hello from SFML"); return 0; } But I keep getting undefined reference even though vs code sees files and lets me jump directly to them using ctrl button. cmake: cmake_minimum_required(VERSION 3.0.0) project(sflmProject VERSION 0.1.0) include(CTest) enable_testing() add_executable(sflmProject main.cpp) set(CPACK_PROJECT_NAME ${PROJECT_NAME}) set(CPACK_PROJECT_VERSION ${PROJECT_VERSION}) include(CPack) compilation error: main] Building folder: firstSFLMProject [build] Starting build [main] Changes were detected in CMakeLists.txt but we could not reconfigure the project because another operation is already in progress. [proc] Executing command: /usr/bin/cmake --build /home/black_wraith/Documents/AIR/S8/RealTime/firstSFLMProject/build --config Debug --target all -j 10 -- [build] -- Configuring done [build] -- Generating done [build] -- Build files have been written to: /home/black_wraith/Documents/AIR/S8/RealTime/firstSFLMProject/build [build] Consolidate compiler generated dependencies of target sflmProject [build] [ 50%] Building CXX object CMakeFiles/sflmProject.dir/main.cpp.o [build] [100%] Linking CXX executable sflmProject [build] /usr/bin/ld: CMakeFiles/sflmProject.dir/main.cpp.o: in function `main': [build] /home/black_wraith/Documents/AIR/S8/RealTime/firstSFLMProject/main.cpp:16: undefined reference to `sf::String::String(char const*, std::locale const&)' [build] /usr/bin/ld: /home/black_wraith/Documents/AIR/S8/RealTime/firstSFLMProject/main.cpp:16: undefined reference to `sf::VideoMode::VideoMode(unsigned int, unsigned int, unsigned int)' [build] /usr/bin/ld: /home/black_wraith/Documents/AIR/S8/RealTime/firstSFLMProject/main.cpp:16: undefined reference to `sf::RenderWindow::RenderWindow(sf::VideoMode, sf::String const&, unsigned int, sf::ContextSettings const&)' [build] /usr/bin/ld: /home/black_wraith/Documents/AIR/S8/RealTime/firstSFLMProject/main.cpp:63: undefined reference to `sf::RenderWindow::~RenderWindow()' [build] collect2: error: ld returned 1 exit status [build] gmake[2]: *** [CMakeFiles/sflmProject.dir/build.make:97: sflmProject] Error 1 [build] gmake[1]: *** [CMakeFiles/Makefile2:839: CMakeFiles/sflmProject.dir/all] Error 2 [build] gmake: *** [Makefile:121: all] Error 2 [build] Build finished with exit code 2 I tried to modify cmake like this but I just have no idea which file should I add: cmake_minimum_required(VERSION 3.0.0) project(sflmProject VERSION 0.1.0) include(CTest) enable_testing() add_library(sfml SHARED /usr/include/SFML/*) add_executable(sflmProject main.cpp) target_link_libraries(sflmProject PRIVATE sfml) set(CPACK_PROJECT_NAME ${PROJECT_NAME}) set(CPACK_PROJECT_VERSION ${PROJECT_VERSION}) include(CPack)
here is an example of cmake file for sfml on linux cmake_minimum_required(VERSION 3.22) project(sfml-program LANGUAGES CXX) add_executable(${PROJECT_NAME} main.cpp) find_package (SFML 2.5 COMPONENTS graphics audio network REQUIRED) target_link_libraries (${PROJECT_NAME} PUBLIC sfml-system sfml-graphics sfml-audio sfml-network)
72,216,482
72,376,069
Running into problem with benders decomposition from scip
I'm running into a strange error when solving a problem with SCIP. This does not happen for all instances, but for a few. I just wanted to ask if someone knows, what the error message means exactly and if I would need to turn off something specifically when solving the Problem with the Bender's Default from SCIP. The exact error message is: [scip_probing.c:259] ERROR: not in probing mode [benders.c:4944] ERROR: Error <-8> in function call [benders.c:1503] ERROR: Error <-8> in function call [benders.c:4406] ERROR: Error <-8> in function call [benders.c:4243] ERROR: Error <-8> in function call [scip_probing.c:259] ERROR: not in probing mode [benders.c:4944] ERROR: Error <-8> in function call [benders.c:1503] ERROR: Error <-8> in function call [benders.c:4406] ERROR: Error <-8> in function call [benders.c:4243] ERROR: Error <-8> in function call [scip_probing.c:259] ERROR: not in probing mode [benders.c:4944] ERROR: Error <-8> in function call [benders.c:1503] ERROR: Error <-8> in function call [benders.c:4406] ERROR: Error <-8> in function call [benders.c:4243] ERROR: Error <-8> in function call [benders.c:3805] ERROR: Error <-8> in function call [scip_benders.c:630] ERROR: Error <-8> in function call [cons_benders.c:555] ERROR: Error <-8> in function call [cons.c:3765] ERROR: Error <-8> in function call [sol.c:1742] ERROR: Error <-8> in function call [primal.c:1593] ERROR: Error <-8> in function call [solve.c:3016] ERROR: Error <-8> in function call [solve.c:3887] ERROR: Error <-8> in function call [solve.c:4187] ERROR: Error <-8> in function call [solve.c:4983] ERROR: Error <-8> in function call [scip_solve.c:2678] ERROR: Error <-8> in function call terminate called after throwing an instance of 'SCIPException' what(): method cannot be called at this time in solution process Aborted (core dumped) and occurs during the presolving process. I'm using the ScipOptSuite 8.0 and implement my problem via C++.
I was able to find the mistake myself. There were some problems with the parameters you can specify within SCIP. For Benders Decomposition you need to turn off the restarts in the solving process, but due to a mistake in the order of putting these parameters it was not turned off.
72,217,399
72,217,637
How do I declare the root as global and set it to null to indicate an empty tree in a structure in c++?
As a beginner in c++, I have encountered a problem trying to implement a structure for binary search tree. Shown below is part of my code but c++ kept reminding me that the "data member initializer is not allowed". #include<iostream> using namespace std; struct BstNode{int key; BstNode*Left; BstNode*Right; BstNode*root = NULL;};
You simply write BstNode *root = nullptr; outside of the struct.
72,218,366
72,220,447
Stack Infix to Prefix not working correctly
I have an assignment to make a program that converts Infix to Prefix in C++. I have written a code to do so but the problem is I am only getting the operands and not the operators in the final result. I have checked my code many time, dry run it, but I cant find the problem. Here is the code: #include <iostream> #include <stack> #include <algorithm> using namespace std; int Prec(char c) { if(c == '^') { return 3; } else if(c == '*' || c == '/') { return 2; } else if(c == '+' || c == '-') { return 1; } else { return -1; } } // prec string InfixToPrefix(string s) { reverse(s.begin(), s.end()); stack<char> st; string res; for(int i=0; i<s.length(); i++) { if((s[i] >= 'a' && s[i] <= 'z') || (s[i] >= 'A' && s[i] <= 'Z')) { res += s[i]; } else if(s[i] == ')') { st.push(s[i]); } else if(s[i] == '(') { while(!st.empty() && st.top() != ')') { res += st.top(); st.pop(); } if(!st.empty()) { st.pop(); } else { while(!st.empty() && Prec(st.top()) >= Prec(s[i])) { res += st.top(); st.pop(); } st.push(s[i]); } } } // for loop while(!st.empty()) { res+=st.top(); st.pop(); } reverse(res.begin(), res.end()); return res; } // InfixToPrefix() int main() { cout<<InfixToPrefix("(a-b/c)*(a/k-l)")<<endl; } Can someone please help? The correct output should be "*-a/bc-/akl" but I am only getting "abcakl". Please help. Thank you.
You need to put the operator logic in the mainloop. #include <iostream> #include <stack> #include <algorithm> using namespace std; int Prec(char c) { if(c == '^') { return 3; } else if(c == '*' || c == '/') { return 2; } else if(c == '+' || c == '-') { return 1; } else { return -1; } } // prec string InfixToPrefix(string s) { reverse(s.begin(), s.end()); stack<char> st; string res; for(int i=0; i<s.length(); i++) { if((s[i] >= 'a' && s[i] <= 'z') || (s[i] >= 'A' && s[i] <= 'Z')) { res += s[i]; } else if(s[i] == ')') { st.push(s[i]); } else if(s[i] == '(') { while(!st.empty() && st.top() != ')') { res += st.top(); st.pop(); } if(!st.empty()) { st.pop(); } else { while(!st.empty() && Prec(st.top()) >= Prec(s[i])) { res += st.top(); st.pop(); } st.push(s[i]); } } else { // added operator logic to the main portion of the parse loop if (!st.empty() && Prec(st.top()) >= Prec(s[i])){ res += st.top(); st.pop(); } st.push(s[i]); } } // for loop while(!st.empty()) { res+=st.top(); st.pop(); } reverse(res.begin(), res.end()); return res; } // InfixToPrefix() int main() { cout<<InfixToPrefix("(a-b/c)*(a/k-l)")<<endl; }
72,218,432
72,333,983
How to read and write on serial ports on Unity Linux through C++ library?
Introduction to the problem I am developing a library in C++ that allows me to communicate with a device connected by USB reading and writing using serial ports, in Windows it works perfectly, but in Linux to be able to communicate with the devices I needed to read and write in the "/dev/tty*" files corresponding to each of them, for this task I use the "open" function to open the corresponding file as shown below: int fileId = open(fileAddress, O_RDWR); But this function returned -1 unless I included the main user in the dialout group using the following command: sudo adduser $USER dialout Problem in Unity With this I verified that everything worked perfectly in my C++ tests, but when I tried to include the library in the Unity project I realized that it failed again as it didn't have access to the serial ports Since I am interested in the communication with the serial port being done through C++, as it is a cross-platform library, I cannot carry out the communication directly to C# Solution attemps I was also looking for some possible solutions to said problem like in this case, but after trying for a while I couldn't get flatpak to find UnityHub since when calling this command: /usr/bin/flatpak run --branch=stable --arch=x86_64 --device=all --command=start-unityhub com.unity.UnityHub it threw me the following error: error: app/com.unity.UnityHub/x86_64/stable is not installed Even though I installed it following the official Unity installation guide for Ubuntu I have also tried adding unity to remote flatpak repositories to see if that was the problem using the following command: flatpak remote-add UnityHub https://hub.unity3d.com/linux/repos/deb But it threw the following error: error: GPG verification enabled, but no summary found (check that the configured URL in remote config is correct) Final question In summary, my main question would be, what exactly should I do to be able to enable read and write permissions for serial ports in Unity and/or what would be the best way to solve this problem? EDIT: As I said in the comments, I already tried to add the user to dialout but apparently Unity was still unable to access the serial ports with said configuration as mentioned in response to this post, a workaround I did was to apply chmod on the specific tty files, the problem is that I have to manually do this and it is not practical when making an Unity build and that any user running the application has to manually find the corresponding tty file and apply chmod to it, if there isn't any other way to do it then, is there at least some way to apply chmod automatically or to solve this problem?
I'm not really sure where the problem lies, but I'll do my best to help. The official Unity installation guide for Ubuntu that you have linked to does not install Unity as a flatpak. That explains why flatpak tells you that it is not installed. The issue you're linking to is describing how flatpak's sandboxing affects Unity when accessing serial ports. Unless you followed a different tutorial than what you linked, this should not apply to you. I think your problem is that permissions on Ubuntu are not set up for serial port access by default. There is no "automatic" way to fix this, because it requires root permissions to change. What you could do, is bundle in an "installer" shell script with your program, and run that whenever you need the permissions to be changed. Command line version #!/bin/sh sudo usermod -a -G dialout "$USER" Graphical version (popup asking for password) #!/bin/sh pkexec usermod -a -G dialout "$USER" This isn't 100% portable, because not all Linux distributions use the dialout group, (for example, Arch Linux uses uucp) but it's probably good enough for your purposes on Ubuntu.
72,218,482
72,218,640
Accessing element of array of pointers to member functions
I am having some troubles with member function pointers. How do I fix this, and why doesn't this work? The issue is inside main()... or so I am guessing! #include <iostream> #include <functional> template<typename T> using FnctPtr = void(T::*)(); // pointer to member function returning void class Base { public: Base() : vtable_ptr{ &virtual_table[0] } {} void foo() { std::cout << "Base"; } void x() { std::cout << "X"; } private: // array of pointer to member function returning void inline static FnctPtr<Base> virtual_table[2] = { &Base::foo, &Base::x }; public: FnctPtr<Base>* vtable_ptr; }; class Derived : public Base { public: Derived() { vtable_ptr = reinterpret_cast<FnctPtr<Base>*>(&virtual_table[0]); } void foo() /* override */ { std::cout << "Derived"; } public: inline static FnctPtr<Derived> virtual_table[2] = { &Derived::foo, &Base::x }; }; int main() { Base* base = new Base(); base->vtable_ptr[0](); // Issue here delete base; }
The type of vtable_ptr is void (Base::**)() while the type of base->vtable_ptr[0] is void (Base::*)(). The syntax that you're using for the call is incorrect. How do I fix this The correct syntax of using the pointer to member function void (Base::*)() in your example would be as shown below: (base->*(base->vtable_ptr[0]))(); Note that there was no need for the Derived class in the minimal reproducible example that you've provided. Working demo
72,218,980
72,222,512
GCC v12.1 warning about serial compilation
I have upgraded my whole arch linux system today (12th May, 2022). gcc was also upgraded from v11.2 to v12.1. I tried compiling some of my programs with g++ (part of gcc compiler collection) by the following command: g++ -O3 -DNDEBUG -Os -Ofast -Og -s -march=native -flto -funroll-all-loops -std=c++20 main.cc -o ./main The program compiled perfectly and ran as excepted without any errors, but I got a warning: lto-wrapper: warning: using serial compilation of 2 LTRANS jobs But, when the same program was compiled using v11.2 it produces zero number of errors and warnings. My Questions: What is the meaning of this warning? How can I fix this? Is this warning occurred due to upgrading gcc version to v12.1 Here's the g++ configuration on my machine: $ g++ -v Using built-in specs. COLLECT_GCC=g++ COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-pc-linux-gnu/12.1.0/lto-wrapper Target: x86_64-pc-linux-gnu Configured with: /build/gcc/src/gcc/configure --enable-languages=c,c++,ada,fortran,go,lto,objc,obj-c++ --enable-bootstrap --prefix=/usr --libdir=/usr/lib --libexecdir=/usr/lib --mandir=/usr/share/man --infodir=/usr/share/info --with-bugurl=https://bugs.archlinux.org/ --with-linker-hash-style=gnu --with-system-zlib --enable-__cxa_atexit --enable-cet=auto --enable-checking=release --enable-clocale=gnu --enable-default-pie --enable-default-ssp --enable-gnu-indirect-function --enable-gnu-unique-object --enable-linker-build-id --enable-lto --enable-multilib --enable-plugin --enable-shared --enable-threads=posix --disable-libssp --disable-libstdcxx-pch --disable-werror --with-build-config=bootstrap-lto --enable-link-serialization=1 Thread model: posix Supported LTO compression algorithms: zlib zstd gcc version 12.1.0 (GCC)
Apparently that is a recent change in the -flto option. With a little bit of variation in the google search I was able to find this mail conversation: Likewise if people just use -flto and auto-detection finds nothing: warning: using serial compilation of N LTRANS jobs note: refer to http://.... for how to use parallel compile [...] That is, teach users rather than second-guessing and eventually blowing things up. IMHO only the jobserver mode is safe to automatically use. So this is about using the -flto options correctly. I could not manage to easily get a GCC 12 on my system and thus could not try it myself, but you can try -flto=1 or -flto=auto to get rid of the warning. Anyway it seems that this warning is rather harmless. It just tells you that GCC uses 2 threads in parallel to do the link time optimization. The exact semantics and effects of the -flto is (together with the other optimization options) described in detail in the GCC manual. By the way you should not spam optimization options like you do in your command line. For example specifying multiple -O... options will only have the effect of the last one of them. Unless you know exactly what you are doing and have carefully read the manual, just stick to use -O3 and you will be fine.
72,220,097
72,220,162
Optimisation and strict aliasing
My question is regarding a code fragment, such as below: #include <iostream> int main() { double a = -50; std::cout << a << "\n"; uint8_t* b = reinterpret_cast<uint8_t*>(&a); b[7] &= 0x7F; std::cout << a << "\n"; return 0; } As far as I can tell I am not breaking any rules and everything is well defined (as noted below I forgot that uint8_t is not allowed to alias other types). There is some implementation defined behavior going on, but for the purpose of this question I don't think that is relevant. I would expect this code to print -50, then 50 on systems where the double follows the IEEE standard, is 8 bytes long and is stored in little endian format. Now the question is. Does the compiler guarantee that this happens. More specifically, turning on optimisations can the compiler optimise away the middle b[7], either explicitly or implicitly, by simply keeping a in a register through the whole function. The second one obviously could be solved by specifying volatile double a, but is that needed? Edit: As an a note I (mistakenly) remembered that uint8_t was required to be an alias for unsigned char, but indeed the standard does not specify such. I have also written the question in a way that, yes the compiler can ahead of time know everything here, but modified to #include <iostream> int main() { double a; std::cin >> a; std::cout << a << "\n"; unsigned char* b = reinterpret_cast<unsigned char*>(&a); b[7] &= 0x7F; std::cout << a << "\n"; return 0; } one can see where the problem might arise. Here the strict aliasing rule is no longer violated, and a is not a compile time constant. Richard Critten's comment however is curious if the aliased data can be examined, but not written, is there a way one can set individual bytes, while still following the standard?
More specifically, turning on optimisations can the compiler optimise away the middle b[7], either explicitly or implicitly, by simply keeping a in a register through the whole function. The compiler can generate the double value 50 as a constant, and pass that directly to the output function. b can be optimised away completely. Like most optimisation, this is due to the as-if rule: [intro.abstract] The semantic descriptions in this document define a parameterized nondeterministic abstract machine. This document places no requirement on the structure of conforming implementations. In particular, they need not copy or emulate the structure of the abstract machine. Rather, conforming implementations are required to emulate (only) the observable behavior of the abstract machine as explained below. The second one obviously could be solved by specifying volatile double a That would prevent the optimisation, which would generally be considered to be the opposite of a solution. Does the compiler guarantee that [50 is printed]. You didn't mention what compiler you are asking about. I'm going to assume that you mean whether the standard guarantees this. It doesn't guarantee that universally. You are relying on several assumptions about the implementation: If sizeof(double) < 8, then you access the object outside of its bounds, and behaviour of the program is undefined. If std::uint8_t is not an a type alias of unsigned char, then it isn't allowed to alias double, and the behaviour of the program is undefined. Given the assumptions hold and thus behviour is well-defined, then the second output will be of a double value that is like -50, but whose most significant bit(s from 8th forward) of the byte at position 7 will have been set to 0. In case of little endian IEEE-754 representation, that value would be 50. volatile is not needed to guarantee this, and it won't add a guarantee in case the behaviour of the program is undefined.