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,571,727
73,572,557
Why create a struct of function pointers inside a class?
I was digging around in the Vulkan backend for the Skia graphics API, found here, and I don't understand a piece of code. Here's the smallest code example: struct VulkanInterface : public SkRefCnt { public: VulkanInterface(VulkanGetProc getProc, VkInstance instance, VkDevice...
With regular polymorphic inheritance struct Base { virtual ~Base() = default; virtual void foo(); // ... }; struct D1 : Base { void foo() override; // ... }; struct D2 : Base { void foo() override; // ... }; You cannot assign to base class without slicing: D1 d1; Base b = d1; b.foo(); // ...
73,572,153
73,709,992
Why file sys/types.h doesn't contain function definition of major(dev_t dev)?
An error is being reported when I use the function major(st_dev) in my code: "‘major’ was not declared in this scope" Looking up documentation in the man page, it suggests that the file sys/types.h contains the definition major(dev_t dev). When I check the file /usr/include/sys/types.h on Linux version 5.10.76-linuxkit...
The BSD include file <sys/types.h> originally created in 1982. On Linux, the helper include <sys/types.h> also includes the <features.h> file. The provided function of this file has changed over time on Linux. That documentation is old, as it refers to BSD_SOURCE. In current versions, BSD_SOURCE is an alias for _DEFAUL...
73,572,299
73,572,353
How to unset -fstack-protector flag with g++?
When I launch g++, I see a lot of default flags : -mtune=generic -march=x86-64 -fasynchronous-unwind-tables -fstack-protector-strong -fstack-clash-protection -fcf-protection. Anyone knows how to unset -fstack-protector-strong ? Thx!
You undo that option with -fno-stack-protector or -fstack-protector if you only want the basic protection. Reference: https://gcc.gnu.org/onlinedocs/gcc/Instrumentation-Options.html UPDATE: The option -fno-stack-protector is really not documented explicitly. It is part of the generic options handling of gcc. As the g...
73,572,645
73,572,921
STD flexible data structure? c++
I'm using nlohmann json objects, since they can add key-value pairs after runtime (and can readily be serialized)... Though I realize this may sacrifice speed. Are there any data structures, of similar flexibility, that are from standard c++ libraries? string character_new() { json j; j["level"] = 1; j["ma...
You have the building blocks in the standard but you would have to wrap them up as they will lack the niceties of nlohman and perhaps some functionality too, as serialization. One general option would be using using AnyMap = std::unordered_map< std::string, std::any >; However std::any is knowingly (and understandabl...
73,572,719
73,572,838
How to simulate reference of a type with C++ templates?
I want to wrap a reference of a type with a class to add other functionality to it, something like below, but I don't want to force the use of a function or operator to access base type methods. class A { private: int fX; public: void SetSomething(int x){ fX = x; } int GetSomething() { r...
Unfortunately, transparent proxies are not currently possible in C++. You can either inherit from the type, implement operator-> or recreate the whole interface. I usually rewrite the whole interface in the reference type.
73,573,133
73,573,256
How to set debug flags correctly in a Cmake project compiled with Visual Studio
I have a C++ CMake project that is compiled both on Linux and Windows. On Windows, this is done via Visual Studio/MSVCC. In CMAKE and in VS, the build is set up as Debug, but it seems that no debug symbols are ever being made in the VS build - so debugging is impossible. When looking over the Detailed output for VS, I ...
You have to compile with a different mode set with CMAKE_BUILD_TYPE as in cmake -DCMAKE_BUILD_TYPE=DEBUG <sourcedir> You never set those flags directly. If you want to add a new flag to a debug mode like for example a stack protector, you should use the *_INIT variables. You can further distinguish which OS you are ru...
73,573,498
73,573,563
Is 'const T*' a cv-unqualified type?
In C++ standard there is much wording including the term "cv-qualified" and "cv-unqualified". It's already known that a cv-qualified type is a type contains a set of cv-qualifiers: one of {"const"}, {"volatile"}, {"const, volatile"}, {" "}. But I get confused when the type returned by std::remove_cv_t<const T*> is actu...
But I get confused when the type returned by std::remove_cv_t<const T*> is actually const T* not T*. Why? const on the left is kind of a lie. If you use right hand const it makes a lot more sense. const T * can be rewritten as T const * and when read from right to left is "non-const pointer to a const T", so it is ...
73,574,336
73,574,571
How to write a custom deleter that works with multiple inheritance?
I have a program which uses a custom allocator and deallocator to manage memory. I've recently encountered a leak that has lead me down a huge rabbit hole that end with custom deleters being incapable of handling multiple inheritance. In the code sample below: #include <iostream> #include <memory> using namespace st...
You can do it this way: void* dptr = dynamic_cast<void*>(ptr); ptr->~B(); operator delete(dptr, Arena()); Live demo Note you need to dynamic_cast before destroying the B object. Without RTTI things get hairy. I assume that in your real code you need the identity of the arena object (otherwise it would be trivial to de...
73,575,450
73,578,196
modern cmake way to add glew and other opengl stuff
I'm create new edu project. Here is the project structure: ├── 3rd-party │ ├── glew │ ├── glfw │ ├── CMakeList.txt ├── src │ ├── main.cpp ├── CMakeList.txt the 3rd-party Cmakelist looks like this: # GLFW add_subdirectory(glfw) # GLEW find_package(GLEW REQUIRED) I installed them simply with commands from gith...
Update: First off, see this question thread about cmake and glew. I'm thinking whether this question is a duplicate or not now... Quoting from the maintainer of the library who wrote in this GitHub issue: For the purpose of a git submodule, I'd recommend using: Perlmint/glew-cmake rather than this upstream repository....
73,575,807
73,575,862
#define or constexpr, which is more suitable here to maximal efficiency?
I have a constant string value std::string name_to_use = ""; I need to use this value in just one place, calling the below function on it std::wstring foo (std::string &x) {...}; // ... std::wstring result = foo (name_to_use); I can simply not declare the variable and use a string literal in the function call instead...
If you #define it to "", then at each call there'll be a conversion from c-string to std::string, which is pretty inefficient. However, you can (usually) pass macro defines as arguments to compiler, which helps customization. Even in that case, it makes sense to write the static constexpr std::string name_to_use. With ...
73,576,294
73,576,384
return class by value or by reference
I was checking a book of c++ and the put a function that is designed to make the class functions cascadable. In this book they conventionally make function inside the class to return a reference of the class rather than the class value. I tested returning a class by value or by reference and they both do the same. What...
First read What's the difference between passing by reference vs. passing by value? Now that you're done reading, let's try a slightly more complicated example so we can really see the difference: int main(){ a A; A.set(13.0).set(42).print(); A.print(); return 0; } If we return by reference A will be m...
73,576,350
73,576,372
Output does not include all input for my array
I have this program that is barely started: #include <iostream> #include <iomanip> #include <ctime> #include <string> using namespace std; class Grade { public: string studentID; int userChoice = 0; int size = 0; double* grades = new double[size]{0}; }; void ProgramGreeting(Grade &student); void ...
Your Grade class is allocating an array of 0 double elements (which is undefined behavior), and then your GetScores() function does not reallocate that array after asking the user how many scores they will enter, so you are writing the input values to invalid memory (which is also undefined behavior). Even if you were ...
73,576,637
73,576,681
Getting very strange results when I try to add multiple products
I'm taking my first C++ class in college so I'm a total newbie here. I'm trying to make a program that prompts the user to input a number of Dimes, Nickels, and quarters. Then, the program will take those values, multiply them to the values of the coins themselves, then find the total sum of cents. Lastly, the program ...
Variables do not work the way you assume. When you do: int quarters; int quarters_value = 25; int quarter_product = quarters * quarters_value; cin >> quarters; Everything goes from top to bottom. It means that once you input a value for quarters (cin >> quarters), variable quarter_product has already been assigned. Ch...
73,576,743
73,576,959
Unable to link imm32.dll in Visual Studio
I'm trying to use a ImmGetContext() from <imm.h> in a Visual Studio 2022 project, which gives the following errors: 1>Project.obj : error LNK2019: unresolved external symbol ImmGetContext referenced in function "void __cdecl activeWindowChangeHandler(struct HWINEVENTHOOK__ *,unsigned long,struct HWND__ *,long,long,unsi...
Seems like I'm doing it in a totally wrong way. Adding #pragma comment(lib, "imm32") to the code have solved the problem. Thanks to ImmGetContext returns zero always
73,576,918
73,577,247
How to define preprocessed global macros in Visual Studio 2022
I want to have a global macro in my program (PI 3.14). I read that you have to go to preprocessor->preprocessor definitions->edit and from there you can add your macros. But how do you actually set what the macro is? I've added the macro PI in the top left. It shows up in my program as equaling 1. How do I make it equa...
Please refer to the link:/D (Preprocessor Definitions) /D name is equivalent to /D name=1. use the way 273K said or in properties->C++->command line: /D PI=3.14
73,576,943
73,576,960
How to break out of a nested loop?
Is there any way to break this without if/else conditionals for each layer? #include <iostream> using namespace std; int main() { for (int i = 0; i < 20; i++) { while (true) { while (true) { break; break; break; } } } ...
You can wrap the logic in a function or lambda. Instead of break; break; break; (which won't work) you can return;. #include <iostream> using namespace std; int main() { auto nested_loops = [] { for (int i = 0; i < 20; i++) { while (true) { while (true) ...
73,577,216
73,577,244
How can I make std::thread not struck the pragma?
I want to design a timer class, there is a function, which sleep some seconds, then call other function. please see the code: #include <thread> #include <iostream> void func() { printf("timer thread function called\n"); } class Timer { public: template <typename Fn> void sleep_start(int sec, const Fn& f) { ...
You call td_.join() early, sleep_start does not exit until thread finishes. class Timer { public: template <typename Fn> void sleep_start(int sec, const Fn& f) { printf("sleep %d\n", sec); td_ = std::thread([sec, f]() { std::this_thread::sleep_for(std::chrono::seconds(sec)); f(); }); } ~Timer() { ...
73,577,404
73,577,422
How to compare data type of a tuple parameter?
How i could compare the data type of each tuple argument? enum WinGetCmds { WINGET_TITLE, WINGET_CLASS }; template <typename... Args> auto WinGet(WinGetCmds cmd, Args&&... args) { auto pack = std::make_tuple(std::forward<Args>(args)...); switch (cmd) { case WINGET_TITLE: { auto arg_1 ...
What other way I could compare the data type of arg_1? The problem is that arg_1 is an expression when you use it in an expression. That is, you cannot use it as a template type parameter for is_same which is what the error is trying to say. To solve this, you could use, decltype(arg_1). Working demo
73,577,434
73,577,629
Disregarding more particular ISA's, is it incorrect to use char argc instead of int argc
For example, on an x86 architecture, where chars are represented as 1 byte, as long as you don't have more than 127 or 255 (depending on how its represented) arguments passed on the stack, shouldn't this be possible. Could this cause issues with alignment for the stack since argv would be 8 bytes to argc's 1 byte vs 8 ...
is it incorrect to use char argc instead of int argc Maybe. C allows various argument parameter sets with main() with "... or in some other implementation-defined manner.". char argc would not be outright non-conforming as it may be allowed on that implementation, but certainly not a portable usage as ... main(char ...
73,577,664
73,577,888
For C++ vector initialization, what's the difference between "vector<int>v = n;" and "vector<int>v(n);"
(English is not my native language; please excuse typing and grammar errors.) I'm trying to create a vector<int> object with known length n. I knew that I could do this by vector<int> v(n); or vector<int> v = vector<int>(n);. However, when I tried to do it by vector<int> v = n;, I got an Compile Error. In my previous e...
Case 1 Here we consider the statement: vector<int> v = n; //this is copy initialization The above is copy-initialization. But the constructor for std::vector that take size as argument is explicit and hence cannot be used here, and so this fails with the error that you're getting. Case 2 Here we consider the statemen...
73,577,933
73,577,997
C++ return type pointer to a structure leetcode
I need help with a return value for one of the leetcode questions I am attempting. I am instantiate a structure and then return the pointer to the structure. TreeNode* deserialize(string data) { TreeNode r(data[0] - '0'); TreeNode* root = &r; return root; } But this gives me the error "stack use after sco...
Variables only exist in their respective scope. The scope of your variable r is the function deserialize, meaning that the memory automatically allocated on the stack upon entering the function will be deallocated upon leaving it. The pointer to this structure you are returning will then be dangling, which means that i...
73,578,052
73,578,078
How to structure my for-loop correctly so my program runs?
So i have a function, string update_name(string names[], int size), which I wanted to let the user pick one of the three names they previously inputted, and change one of the name (picked by the user). However, when I try to run this program, it does ask me which name i wish to change, i type a name, but then it goes t...
To fix your for-loop you need to have a correct condition statement and increment expression. To loop from 0..=3 you would structure the for-loop as: for (int i = 0; i < 4; ++i) { ... } In general: You have a init-statement that initializes a variable that will exist only for the scope of the for-loop. eg: int i = 0 ...
73,578,133
73,578,229
Visual Studio throws "undeclared identifier" from predefined string macro
I have the following preprocessed macro defined under C/C++ -> Command Line -> Additional Options: /D NV_WORKING_DIRECTORY="C:/foo" An image from the project settings: I have the following code: std::string path = NV_WORKING_DIRECTORY; When I compile I get this error: 'C': undeclared identifier. Weirdly, with cer...
When you use /D in the C/C++ -> Command Line -> Additional Options, the value is expected to be wrapped in a string. E.g. the following means the value of XXX will be YYY: /D XXX="YYY" Therefore if you need the value of the preprocessor definition to contain the quotes, you need to add and escape them: /D NV_WORKING_D...
73,578,359
73,579,408
Program to output repeated integers from user-inputted group in ascending order is not printing contents of array
I have been tasked with writing a simple program that takes in two groups of integers as user input, with the size of those groups being inputted by the user as well, then prints all integers that appear more than once in ascending order. For example, an input of 5 7 20 8 7 15 3 8 14 7 would result in an output of Ans...
It was n't a valid program to do the tests. I slightly modified it. I used vector for array. However your algorithm is correct. Now it works ok. Please check the source and try it in your compiler. #include <iostream> #include <vector> #include <algorithm> using namespace std; void swap(int *num1, int *num2) { in...
73,579,436
73,586,462
Unable to import compiled javascript file from Emscripten for WebAssembly (C++ wrriten) to React
Hi I've compiled the C++ file via emcc (emscripten frontends). The output I expected is one .wasm file and .js file to implement javascript. I build React application which try to import WebAssembly via .js module like below. (./wasm/dist/my-module is .js module compiled by emcc) import { useEffect } from 'react'; impo...
Have a look at this. Basically, compile into -o something.mjs and add -s SINGLE_FILE=1. This will give you a single .mjs instead of a regular pair of .js and .wasm, avoiding all the trouble.
73,579,640
73,579,748
Assigning one struct variable to the another varible of a same type which is in different struct in C++
Can we assign one variable from a structure to another variable of a same type which is in a different struct, directly in C++? Such as: struct Test1 { inx x1; int y1; } struct Test2 { int x2; int y2; } void trialStruct(Test2& origin2) { Test1 origin1; origin1.x1 = origin2.x2; origin2.y1 = origi...
Can we assign one variable from a structure to another variable of a same type which is in a different struct, directly in C++? Yes, the type of origin1.x1 and origin2.x2 is same(both are int) and we can assign origin2.x2 to origin1.x1 as you've done in your example. Note also that instead of assigning individual me...
73,579,667
73,579,745
implicitly-declared ‘...’ is deprecated [-Wdeprecated-copy] in compiling TinyMT on GitHub
I have looked into similar questions on StackOverflow, but I couldn't figure out what to do. The following is the error I faced (some texts are in Japanese). $ make g++ -Wall -Wextra -O3 -I../include -D__STDC_CONSTANT_MACROS -D__STDC_FORMAT_MACROS -o tinymt32dc tinymt32dc.cpp parse_opt.o -lntl 次のファイルから読み込み: tinymt32...
The warning says tinymt32 class has a user-defined copy constructor but there is no copy assignment operator defined. That is in violation of rule of three/five and signals potential troubles with management of any resources tinymt32 might hold. So this warning is not targeted at the user of the library, but its author...
73,579,686
73,580,151
Why int[] cannot be converted to T*&?
template <class T> void func(T*& a) { } int main() { int a[5]; func(a); // <-- Error here: no matching function for call to ‘func(int [5])’ return 0; } why int[] is not implicitly converted to int* so that it can match template functions?
There are actually two issues. One is about how references work, and the other is about how templates work. Let's examine them separately. Consider these non-template functions: void foo(int*&) {} void bar(int* const &) {} void baz(int*) {} The second and third functions accept array arguments, but the first one does ...
73,579,779
73,598,230
Use Resharper with the C language in Visual Studio?
I recently started studying at university which granted me a student license for all JetBrains products. I thought it would be an excellent chance to try Resharper for C# and C++. I am now taking a course in C. From what I searched online, Visual Studio can work with C code. However, it seems that Resharper is only mea...
Turns out this is a Visual Studio inspection and not a ReSharper one. Disabling Visual Studio IntelliSense via Options | Text Editor | C/C++ | Advanced | Browsing/Navigation | Disable Database solves the issue.
73,580,058
73,581,505
Is there a better way to split a container of a non-movable type based on a predicate
I want to ask for an alternative solution to this problem. I am dealing with this C/C++ style interface that has this non-moveable type NonMovableType defined roughly as follows: union union_type { int index; const char* name; }; struct NonMovableType { std::initializer_list<union_type> data; }; This is somet...
Is it really a performance problem or are you trying to optimize in advance? As for a general answer: it really depends. I would probably try to achieve everything in a single pass (especially if the original container has a lot of elements), e.g. for (const auto& el : container) { if (el.data.size()) out1.push_back(...
73,580,320
73,580,525
Using memcpy to switch active member of union in C++
I know about the memcpy/memmove to a union member, does this set the 'active' member? question , but I guess my question is different. So: Suppose sizeof( int ) == sizeof( float ) and I have the following code snippet: union U{ int i; float f; }; U u; u.i = 1; //i is the active member of u ::std::memcpy( &u.f...
Regardless of the union, the behaviour of std::memcpy is undefined if the source and destination overlap. This is the case for every member of the union, and it would not be different if the sizes weren't the same. If you were to use std::memmove instead, there is no longer an issue due to the overlap, and it also does...
73,580,410
73,584,213
How to make to_string stop at the right time when processing fractional parts
I wrote a to_string function for my string library and the main part of it looks like this template<typename T> inline string num_base(T num,size_t radix,const string radix_table)noexcept{ string aret; do{//do while, also has a return value when num is 0 T first_char_index{}; if constexpr(::std:...
Originally from my friend's idea, I now renamed the original to_string to to_string_rough and built the to_string from to_string_rough and from_string_get! Under the assumption that decimal is used (for ease of example), to_string will first obtain the processing result of to_string_rough and attempt to process the cas...
73,580,576
73,581,711
dyld[49745] missing symbol called using c++ swig with node.js by calling a function out of the library
I try to create an example using SWIG and NodeJS on my M1 (arm64) Mac, but I want to mention this as early as possible: this issue appears also on an Intel (x64) Mac. I create my simple example Files like this: example.h #pragma once class Die { public: Die(); ~Die(); int foo(int a); }; Die* getDie(); //...
Your question is an interesting take on a FAQ on this site: What is an undefined reference/unresolved external symbol error and how do I fix it?. The role of SWIG is indeed to generate glue code between Node.js and C++ code. But it does only that. If you inspect the .dylib file that is associated with your NodeJS modul...
73,581,513
73,581,570
Why does my const reference variable, assigned via a getter that returns a const reference, not have the desired value?
I have the following code: #include <iostream> class Walltimes { private: double walltime = 0.0; public: void update_walltime(double delta) { walltime += delta; } double const& get_walltime() const { return walltime; } }; int main(){ Walltimes myObj; double ...
Why does t1 know that the walltime will eventually be 4.78? Because t1 is a reference to the data member walltime for object myObj and so when you wrote myObj.update_walltime(4.78); , you updated the data member walltime of myObj which means the change will be reflected in t1 also as t1 is an alias for walltime.
73,581,608
73,583,329
Wrap Callback API into Coroutine-based Iterable
I want to warp a typical C callback API that generates multiple int values into an iterable in the fashion of std::generator<int> (see p2502r1). API looks like: typedef void (*Callback)(int); void api(Callback callback) { callback(1); callback(2); callback(3); } The API wrapper should behave like: for(int i...
What you want isn't really possible with co_await-style coroutines. To do this, you would need to be able to suspend within the callback such that it also suspends the api function as well. co_await-style coroutines can't do that.
73,582,344
73,582,433
crash for C++ map when deleting via iterator
I have the following code which crashes #include <map> #include <iostream> using namespace std; int main() { map<int,int> m; m[1]=2; m[2]=3; m[3]=4; m[4]=5; /* m.insert(std::make_pair(1,2)); m.insert(std::make_pair(2,3)); m.insert(std::make_pair(...
Your map is this (showing the keys only) { 1, 2, 3, 4 } You then loop through, find the 3, and erase the next element. Leaving this { 1, 2, 3 } Now you start from the beginning again, find the same three again and delete the next element, but this time there is no next element. Therefore you get a crash,
73,583,978
73,584,075
C++ assigning member function pointer to non-member function pointer
Hy everyone, I am quite new with OOP in C++ [go easy on me :) ] and I am trying to build a class in which a class member function needs to be taken from outside the class. I thought of doing it by declaring a function pointer member and creating a member function that takes as input a pointer to the function that I wan...
There are a couple of issues. First, 'pointer-to-member' types are an advanced (and, dare I say, esoteric) feature for accessing member functions as pointers. Since you've got an std::function (which, when it comes down to it, is some sort of ordinary function, not a member function), you don't need pointer-to-member. ...
73,584,099
73,588,317
"unknown error" from std::error_code on Windows
I have a strange problem with system error messages obtained from std::error_code on Windows. When I build and run test program 1 (see below) using my locally installed Visual Studio, error messages for all system error codes come out as "unknown error". On the other hand, when building and running the same program on ...
Ok, the problem in my case is that the system locale is set to "en-GB" and not "en-US". If I pass language identifier 2057 (en-GB) to FormatMessage() I get no error message, but if I pass 1033 (en-US), I do. So far, I have not been able to change the system-level locale, but even if it can be done, it seems rather subo...
73,584,103
73,584,527
how make pointers to follow another pointer in c++
I want to write a program that uses Pointers and when I change the value of a pointer, the others follow that pointer; here is my code: int * M1 = new int(1) ; int * M2 = new int(2) ; int * M3 = new int(3) ; int * M4 = new int(4) ; int * M5 = new int(5) ; int * M6 = new int(6) ; int * M7 = n...
I don't think you can do what you're asking in the way you're asking it. Pointers are kind of like labels for memory locations, and moving one label doesn't change the location any of the other labels are pointing to. Let's visualize the starting state: 1 <- M1 2 <- M2 3 <- M3 4 <- M4 5 <- M5 6 <- M6 7 <- M7 8 <- M8 9 ...
73,584,172
73,584,663
Templates and type erasure - Why does this program compile?
I have written an example type erasure program, but I noticed something that seemed strange. The code compiles - and I believe it shouldn't. More likely, it does something that I don't understand which enables it to compile. Here is a MWE. #include <iostream> #include <memory> #include <string> #include <vector> clas...
I believe I have figured it out. Someone may correct me if this is wrong. Starting from cout << document this is, in terms of the types involved cout << vector<Object<T>> This is implicitly converted to cout << Object<vector<Object<T>>> I'll just add this line, which we will refer back to later. Since cout is a type...
73,585,164
73,585,275
How to wait for QThread eventDispatcher being ready?
I'm using QThread's event loop to communicate with worker threads. I noticed that I can't use the thread's event loop just after a start. The following code does not work, as threadEventDispatcher appears to be NULL. QThread *thread = new QThread; thread->start(); auto* threadEventDispatcher = thread->eventDispatcher()...
Simply connect to QThread::started() signal.
73,585,447
73,585,540
variable list argument function returning address
Hello guys my program is not printing the maximum value it is printing some garbage value or address. #include <iostream> #include <cstdarg> int findmax(int, ...); int main(int argc, char *argv[]) { std::cout << findmax(9, 255, 86, 4, 89, 6, 1, 422, 5, 29); } int findmax(int count, ...) { int max, val; v...
for (int i = 0; i < count; ++i) { max = va_arg(list, int); val = va_arg(list, int); if (max < val) max = val; } In this code you take two arguments but iterate the index by one. va_arg always takes the next element, so you end up with taking values beyond the variadic function argument list. You may iterat...
73,586,048
73,587,851
Getting a window's pixel format on GLFW in linux
I want to get a GLFW window's pixel format. I'm using ubuntu so win32 functions are out of the picture. I've stumbled upon this question but there are only win32 answers and there is an answer that uses HDC and PIXELFORMATDESCRIPTOR which I don't have access to (Since I will not be using the function permanently I rath...
That is outside the scope of GLFW as can be read here: Framebuffer related attributes GLFW does not expose attributes of the default framebuffer (i.e. the framebuffer attached to the window) as these can be queried directly with either OpenGL, OpenGL ES or Vulkan. If you are using version 3.0 or later of OpenGL or Ope...
73,586,598
73,588,566
How to Filter directories in a QFileDialog then set filter for filenames in selected directory
I'm trying to create a QFileDialog that will eventually select a file based on a filter, but I want to limit the user to only be able to select from certain directories from a common directory and I haven't had any luck. I've tried Filtering directories displayed in a QFileDialog, qfiledialog - Filtering Folders? and H...
I think I knew where the problem is, first I changed the FileFilterProxyModel to become the default filter, like this: bool FileFilterProxyModel::filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const { QModelIndex index0 = sourceModel()->index(sourceRow, 0, sourceParent); if (!index0.isValid())...
73,587,258
73,587,434
std::sort of std::vector produces illegal elements
I have an application in which std::sort sometimes causes a core dump. I was able to isolate the problem to the following MWE: #include <algorithm> #include <iostream> #include <numeric> #include <vector> class DF { public: DF() = default; std::vector<int> row_mapping; std::vector<int> idx = {0, 1}; ...
The problem is that the comparison function doesn't satisfy the "strict weak ordering" requirement. With the following corrected lambda, everything works: std::sort( begin(row_mapping), end(row_mapping), [&](int i1, int i2) -> bool { std::cerr << "cmp " << i1 << " " << i2 << std::endl; ...
73,587,384
73,587,589
Loading a 2D array from an input file into a Function
I am having trouble loading a 10x10 array from an input file and storing it into an array. I have written this so far: #include <iostream> #include <fstream> #include <string> using namespace std; void LoadImage(const string imagefile, int image[MAXROWS][MAXCOLS]) //Function to load in image { ifstream inputs; ...
The code is generally OK, just following the comments and fixing a few small mistakes should work. Note specially the terminating condition for the following loop: for ( j=0; i < MAXCOLS; j++ ) Should be instead: for ( j=0; j < MAXCOLS; j++ ) This is the reason why you're getting an infinite loop. Here's the complete...
73,587,864
73,588,154
Const array initalize from other const array
const char DICTIONARY[][6] = { "apple", "sands" }; class LetterSet { public: unsigned int bitfield; LetterSet(const char letters[5]) {}; }; const LetterSet words[] = { LetterSet(DICTIONARY[0]), LetterSet(DICTIONARY[1]), }; How can I modify the code above to work in the case where ...
Might not be needed by Carson, but for those looking for a way to transform an array elements to another type at compile time, it's possible using helper templates and std::array. An example: template<class T, std::size_t...Is> auto transform_array_impl(auto&& array, std::index_sequence<Is...>) { return std::array<...
73,588,083
73,591,183
Why is the [[nodiscard]] attribute not transitive?
Consider the following code: [[nodiscard]] float val() { return 3.; } float junk() { return val(); } int main() { junk(); } It seems logical that junk should be required to be marked as [[nodiscard]], yet the above example compiles without any warnings. Put differently, what is the point of val being no discard, if it...
[[nodiscard]] merely prevents the value returned from val to be discarded. junk is using the returned value so all is ok. If you want you can mark junk as [[nodiscard]]. Moreover, note that there is no strong guarantee to get a warning in the first place (cppreference): If a function declared nodiscard or a function r...
73,588,273
73,588,709
How to have a smart pointer to a view object get ownership of the underlying buffer object?
Let's say I have an underlying buffer char *c = new char[100]; which I reference through a View object (which does not take ownership, but offers the actual functionality) View *v = new View(c); Now I would like to construct a smart pointer, such that when dereferenced gives the View* v object, but when destroyed des...
Here's an example of how to do it: #include <iostream> #include <memory> struct A { ~A() { std::cout << "~A()" << std::endl; } }; struct B { ~B() { std::cout << "~B()" << std::endl; } }; int main() { A* pa = new A(); auto deleter = [pa](B* pb) { delete pa; delete pb; }; std::unique_ptr<B, decltyp...
73,589,329
73,591,996
Find the smallest sum of the absolute differences of k pairs of an array
Can anyone help me with this problem? Given n integers and a number k (k<=n/2). Find the smallest sum of the absolute differences of k pairs of an array. Example 1: Input: 5 2 2 5 3 3 6 Output: 1 Explain: |3 - 3| + |6 - 5| = 1 Example 2: Input: 6 3 868 504 178 490 361 603 Output: 462 Explain: |868 - 603| + |504 - 4...
Assuming O(N * K) solution would pass, then we can solve the problem using dynamic programming. Let dp[i][j] be the minimun cost to use the first sorted i numbers, using j pairs. We can write: dp[0][j] = INT_MAX; // for each j between 0 and K. dp[i][j] = std::min(dp[i - 1][j], a[i] - a[i - 1] + dp[i - 2][j - 1]); // fo...
73,589,589
73,589,650
Why doesn't std::stringstream work with std::string_view?
The std::stringstream initialization constructor accepts const string& as a parameter: explicit stringstream (const string& str, ios_base::openmode which = ios_base::in | ios_base::out); This interface was reasonable in C++98, but since C++17 we have std::string_view as a cheaper alternative of ...
At this point (ie: as we approach C++23), there's just not much point to it. Since you used stringstream instead of one of the more usage-specific versions, there are two possibilities: you either intend to be able to write to the stream, or you don't. If you don't intend to write to the stream, then you don't need the...
73,589,746
73,589,765
C++ std::bind to std::function with multiple arguments
This question is going to be very much a duplicate, but I've read many of the examples on stack overflow and the common solution is not compiling for me, and I'm trying to figure out why. So I have a function I want to store in another class, the minimal example of what I'm doing outlined below. It does not compile as ...
Your function has two parameters, so you need two placeholders in your bind expression. std::bind(&ParentClass::someFunction, this, std::placeholders::_2) needs to be std::bind(&ParentClass::someFunction, this, std::placeholders::_1, std::placeholders::_2) Alternatively you can simplify this with a lambda like [this]...
73,589,839
73,589,966
Template Function Specialization - const
Why does template specialization C) work with base template A) but not with template B)? A) template<class t> t* maxn( t*, int); B) template<class t> const t* maxn(const t*, int); C) template<> const char** maxn<const char*>(const char*arr[], int);
First things first, the parameter named arr is actually of type const char**. Now we will see what happens for each case. Case A Here we consider the following: template<class t> t* maxn( t*, int); //primary template template<> const char** maxn<const char*>(const char*arr[], int); //specialization In the above, we'...
73,589,908
73,590,080
The most simplest of C++ RNG questions that I'm embarrassed to come back and ask
sorry for all the horrible questions Ok so basically I have this short little C++ project thats supposed to spit out random 3-digit binary numbers and stop when it finds one that's matching to the binary string you, the user types in. I know something is wrong with the "&" part and really want to know what's wrong even...
first of all , writing using namespace std; is a very bad practice : please refer to Why is "using namespace std;" considered bad practice? second of all using bitwise AND will not give you what you want for the line of code you write which is random = rand() % 2 & rand() % 2 & rand() % 2; then what do you think about...
73,589,982
73,590,302
IPortableDeviceManager::GetDevices returning 0 Devices
I'm currently writing a simple application to retrieve a list of the PnP devices of my computer. To do this, I'm making use of the Windows PortableDeviceApi Library. So far I have the following code: #include <iostream> #include <PortableDeviceApi.h> #include <wrl.h> inline void getDeviceHWIDs() { // Initialize ...
This is expected, Windows Portable Devices provides only a way to communicate with music players, storage devices, mobile phones, cameras, and many other types of connected devices. It will not enumerate all devices on your system. Connect an IPhone and you will see pnp_device_id_count become 1. To enumerate all device...
73,590,083
73,590,151
A question about class member function that returns a structure
I had a trouble when I read C++ Primer Plus. class AcctABC { private: string fullName; long acctNum; double balance; protected: struct Formatting { std::ios_base::fmtflags flag; std::streamsize pr; }; const std::string & FullName() const {return fullName;} long AcctNum(...
This is about qualified names. The fully qualified name of the return struct is AcctABC::Formatting. However the AcctABC:: can be omitted if you are already in the scope of an AcctABC definition. That is why AcctABC:: is not necessary in the SetFormat declaration, or in the body of the SetFormat definition, or the para...
73,590,560
73,629,747
memory assert when delete SkCanvas object
When I use "delete mCanvas" to delete a SkCanvas object, debug with VS2022, I get a memory assert "A breakpoint instruction was executed". From the stack, "skia.dll!SkCanvas::vector deleting destructor(unsigned int)" is being called. Why does this happen? How should we delete SkCanvas object? Thanks
I needed to build skia with extra_cflags=["/MDd"] when in debug mode. This solved my issue.
73,590,673
73,884,475
Converting between the containers with transparent and non-transparent comparators
I have a class A that has a member std::map<std::string, Data, std::less<>> where Data is another class from a library whose source code I'd rather leave intact. I have opted in to use the transparent comparator by using std::less<> as the template argument since I want to be able to benefit from std::string_view. The ...
For whatever reason, this library requires a reference to a map that uses a std::less<std::string> comparator, but you have a map that uses a std::less<void> comparator. As you say, these specialisations of std::map are two unrelated types, so there is no well-defined cast between them. You must create a separate objec...
73,590,799
73,590,850
c++ member function hides global function
This code snippet doesn't compile: struct M { int i; int j; }; void f(M& m) { m.i++; } struct N { M m; void f(int i) { f(m); // compilation error } }; clang says : No viable conversion from 'M' to 'int' Seems my member function hides global function. I changed the error line into ::f(...
c++ member function hides global function The problem is that for the call expression f(m) name lookup finds the member function N::f(int) and so the search/lookup stops. Now this found member function N::f(int) has a parameter of type int but we're passing an argument of type M and since there is no implicit convers...
73,591,088
73,591,457
How to use std::pair with classes?
so I'm experimenting with cvc5 and just wanted to keep track of the Terms in a map so I have created this: std::map<std::string, std::pair<Term, int>> terms; Basically, for I used the name as an index and I store the Term with other info in the map. I have created a subtype of Term called TermStruct and I wanted to cre...
pair has nothing to do with this problem. It is all about map. I see two options. Introduce a default constructor(a constructor without parameters) for TermStruct if you want to use std::map::operator[]. Here's why: termsStructs[str] = std::pair(term, offset) does not insert the pair object right away termsStructs[st...
73,591,406
73,592,321
What is the best way to have different files use different precompiled headers in CMake?
I have a large test suite that is compiled as an executable, that is roughly structured as follows: ProjectRootDir | ---A -> .cpp/h files with a fairly common set of expensive includes | ---B -> .cpp/.h files with a fairly common but different set of expensive includes | (etc.) Using precompiled headers gr...
Just make sure that the source files in A belong to a different target than those in B. You can do this with OBJECT libraries if it isn't the case already: add_library(A OBJECT ...) target_precompile_headers(A PRIVATE expensive_header_a.h) add_library(B OBJECT ...) target_precompile_headers(B PRIVATE expensive_header_...
73,591,783
73,591,813
Does gcc have a extension overload for std::vector::emplace_back?
According to cppreference, std::vector::emplace_back has only one signature, which is: template< class... Args > reference emplace_back( Args&&... args ); And in the description, it says emplace_back is supposed to forward each of its arguments to the constructor of the type in the vector. However, when I tested the f...
foos.emplace_back(foo); // weird That's weird indeed! You ask to emplace_back, meaning you're calling the constructor, and you're passing foo to the constructor. Hence, you're calling the copy constructor. push_back would have done the same! That's an implicitly defined default copy constructor, see cppreference on ...
73,592,249
73,592,267
Do I need to save a code every time I make changes in code (VScode)(c/c++)
I'm new to coding and recently I came across a problem that my code doesn't work unless I save that first so is it necessary to save a code every time I make a change in a code.(vscode)(c)
Usually, C and C++ are compiled, i.e. the file(s) with the source code need to go through a compiler to get translated to machine code. So, the program source needs to be saved first before it can go into the compiler, yes. Most IDEs, like VSCode, will save when you ask them to compile, because that's useful assistance...
73,592,272
73,592,337
c++ how to use template class as [type parameter] when defining template function?
I am trying to write a template function, which could accept generic-typed containers like std::vector/list, to do some work, like this: template<typename T, typename Container> void useContainer(const Container<T>& container) { } Then in main function I can: vector<int> vi; useContainer(vi); // compilation er...
The correct way to do this would be by using template template parameter as shown below: //use template template parameter template< template<typename W, typename Alloc = std::allocator<W>>typename Container, typename T> void useContainer(const Container<T>& container) { } int main(){ vector<int> vi; useCont...
73,592,275
73,592,440
Thread is terminated for no apparent reason
So I am currently making a system to list all visible windows and then choose a random one. The code exists and is working.. in 32-bit. The problem is that it won't work when compiling for 64-bit. It does not even hit my breaking point before terminating the thread. I have also tried using a try block with the same res...
The thread was terminated because the wrong size was passed to the message. The thread hang issue was fixed by using SendMessageTimeout(...); instead of SendMessage(..);. This works because a window was not responding to any messages. (Answer is for people who have the same issue) Thanks to Igor Tandetnik and Peter for...
73,593,245
73,597,773
how to achieve backward compatibility with missing shared library
I upgrade a program that needs to run on both old and new platform. In the new platform, I have new config so certain functions will not get called in the old platform. However, when I run the program on old platform, it complains missing shared library. What I need is something like "lazyload" or "delayload" mechanism...
It looks like your particular linker (you didn't specify which one, but we can guess it might be the default ld.bfd linker) does not support -z nodefs. Try --allow-shlib-undefined to achieve the same result.
73,593,296
73,593,395
Will the buffer be overwritten when async read?
I want to use boost::async_read after async_read_until. async_read_until can write to buffer some data after delimiter. Can i use safely boost async_read after async_read_until with the same buffer and dont lost data that already in buffer?
It depends. There are dynamic buffers (streambuf, dynamic_string_buffer etc) that will retain the information. If you use fixed buffer sequences, you can use Buffer Arithmetic to preserve a part of existing buffer. It might help to realize the flipside: [async_]read_until guarantees completion when the completion cond...
73,593,959
73,594,315
Is there a better way to implement count sort?
The following code implements count sort: an algorithm that sorts in O(n) time complexity, but with a (possibly) heavy memory cost. Is there any better way to go about this? #include <algorithm> #include <iostream> #include <numeric> #include <vector> #include <iterator> int main() { std::vector<int> arr = { 12,31...
with input A[0:n], max_element=k, min_element=0, for the counting sort: time complexity: O(n + k) space complexity: O(k) You can NOT get O(n) time complexity, with O(1) space complexity. If your k is very large, you should not use count sort algorithm. In your code, you use std::vector<std::pair<int, int>> to stor...
73,594,268
73,594,584
Creating a variadic template map of type key to value with nondefault constructor
I'm trying to create a map that can work as such: // I have A, B, and a templated class Processor struct A; struct B; template<class T> struct Processor { Processor(T foo); void SomeFunction(); }; // This is something like how I expect the map to be able to work int main(){ A a; B b; TypeToValMa...
Since you know all the types at compile time, you can store them in a container like std::tuple. If your mapping is always T -> Processor<T>, you can use a class to wrap the tuple like this: template<class... T> struct ProcessorMap : private std::tuple<Processor<T>...> { private: using tuple = std::tuple<Processor<...
73,594,449
73,594,720
How to load mesh in new thread
I am making my first game and I am stuck with one problem. I have a world where you can walk free, but then when you meet the enemy you will switch to battle and when you are switching to battle, I need to load all the models that will be rendered in the battle scene. The loading takes about ~5 seconds and I want to ma...
Assuming you have two windows, you can bind each context of the window to separate threads. Problems will arise if you share data between them (proper locking is mandatory). See glfwMakeContextCurrent: This function makes the OpenGL or OpenGL ES context of the specified window current on the calling thread. A context ...
73,594,528
73,594,540
Code that's inside a for loop and written after the std::accumulate will not execute
I want to write a function calculating the sum of each row of a 2d vector and find the maximum of those sums. I tried to loop through the vector and use std::accumulate to sum up each sub-vector. However, each time the loop increment, the code after the std::accumulate will not execute. For example, in the following co...
Your for loop needs braces { ... } around the body. for (auto x: my_2d_vector) { //mx will not be assigned and it will remain a value of 0. temp = std::accumulate(x.begin(), x.end(), 0); mx = (firstSum < temp) ? temp : firstSum; }
73,594,842
73,595,568
accessing to map in multithreaded environment
In my application, multiple threads need to access to a map object for inserting new items or reading the existing items. (There is no 'erase' operation). The threads uses this code for accessing map elements: struct PayLoad& ref = myMap[index]; I just want to know do I still need to wrap this block of this code insid...
Since there is at least one write operation, i.e. an insert, then you need to have thread synchronization when accessing the map. Otherwise you have a race condition. Also, returning a reference to the value in a map is not thread-safe: struct PayLoad& ref = myMap[index]; since multiple threads could access the value,...
73,594,845
73,594,999
how to call member function if it exists, otherwise free function?
I've got various classes: struct foo final { std::string toString() const { return "foo"; } }; struct bar final { }; std::string toString(const bar&) { return "<bar>"; } struct baz final { std::string toString() const { return "baz"; } }; std::string toString(const baz& b) { return "<" + b.toString() + ">"; } struct...
So you have three overloads of detail::toString_imp: auto toString_imp(const T& obj, int) -> decltype(obj.toString(), std::string()) auto toString_imp(const T& obj, long) -> decltype(toString(obj), std::string()) auto toString_imp(const T& obj, long long) -> decltype(toString_(obj), std::string()) That you call with t...
73,594,911
73,594,941
How do I avoid repetitive code in the case of switch statements which are the same but for some substituted variables/vectors/etc.?
The following snippet is from an inventory system I'm working on. I keep on running into scenarios where I fell I should be able to simple run a for loop, but am stymied by the fact that in different cases I'm using different vectors/variables/etc. I run into this problem just about any time I need to work with a varia...
You're very likely on the right track, this is how we build up the abstractions. A simple way is to define a lambda: // you might refine the captures auto processInventory = [&](auto& inventoryToProcess) { //loop through the inventory... for (int i = 0; i < 6; i++) { //looking for an empty spot ...
73,595,156
73,595,474
Clarify the ambiguity of partial template specialization
I am confused by the error output of GCC for the partial specializations below. // Primary template<class T, class U1, class U2, class... Us> struct S{}; // #1 template<class T, class... Us> struct S<T, T, T, Us...>{}; // #2 template<class T, class U, class... Us> struct S<T, T, U, Us...>{}; // #3 template<class T, ...
Conceptually neither #2 nor #4 is more specialized, because there are lists of template arguments for A such that #2 is viable, but not #4, as well as such sets for which #4 is viable, but #2 is not. In your formal analysis everything looks correct, except that at P4=U3, A4=<aUs...>[0] (<aUs...> is not empty in this c...
73,595,176
73,595,208
Reading files using ifstream.read(buf, length) - receiving corrupted data (most of the time)
I'm currently learning C++ and OpenGL. Now I'm trying to read a complete file into a C style string (to be precise, the file I'm trying to read contains the source code for a GLSL shader). Suppose the following code: std::streamoff get_char_count(const char *path) { auto file = std::ifstream(path); file.seekg(0...
You have to null-terminate the C string. The file has no '\0' at the end, so it is not read from the field, but a C string must be terminated with '\0': auto buf = new char[file_size + 1]; file.read(buf, file_size); buf[file_size] = '\0';
73,595,359
73,595,385
destructor not called for object going out of scope and end of main program
I have the following code #include <bits/stdc++.h> struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode() : val(0), left(nullptr), right(nullptr) {} TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left),...
One of the golden rules of C++, if you use new on something, you also should delete it. When you use new, you are telling the compiler that you are now in charge of managing that variable's lifecycle.
73,595,909
73,596,011
dlopen succeeds (or at least seems to) but then dlsym fails to retrieve a symbol from a shared library
In an attempt to undersand how lazily loaded dynamic libraries work, I've made up the following (unfortunately non-working) example. dynamic.hpp - Header of the library #pragma once void foo(); dynamic.cpp - Implementation of the library #include "dynamic.hpp" #include <iostream> void foo() { std::cout << "Hell...
auto foo = dlsym(lib, "foo"); Perform the following simple thought experiment: in C++ you can have overloaded functions: void foo(); void foo(int bar); So, if your shared library has these two functions, which one would you expect to get from a simple "dlsym(lib, "foo")" and why that one, exactly? If you ponder and ...
73,595,914
73,595,955
C++ Assign a variable to function call that could return void
I'm trying to write a function that measures the time of execution of other functions. It should have the same return type as the measured function. The problem is that i'm getting a compiler error Variable has incomplete type 'void' when the return type is void. Is there a workaround to solve this problem? Help would ...
It's possible to solve this problem using specialization and an elaborate song-and-dance routine. But there's also a much simpler approach that takes advantage of return <void expression>; being allowed. The trick is to fit it into this framework, by taking advantage of construction/destruction semantics. #include <ios...
73,596,143
73,596,218
Is there a way to convert a string into a float without losing accuracy?
I have float values with high precision. When I convert them to a string I lose precision. I am storing this float value in a Json::Value object. And I need to later take the float back out of the Json::Value object without losing precision. I am using this float value to predict values. When the float loses precision ...
updated answer: as @njuffa mentioned, your demo code maybe issue of textual representation, i write code to test it as below float num = 0.0874833928293906f;//maybe this is the precision lost place, it's not about jsoncpp Json::Value weight(num); float back_num = weight.asFloat(); if (memcmp(&num,...
73,596,563
73,596,618
Why do I have to use an initialization list to use constructor delegation?
I know we have to use an initialization list to use constructor delegation. But why can't we use it in another way? For example, in the code below, constructor delegation is not working. It is not setting the health=pHealth. But the cout << "I am the main constructor" is printing on the console. It means the constructo...
Your program is creating two objects. using x using "Player(40);" inside constructor Sample: #include <iostream> using namespace std; class Player { int health; public: Player(int pHealth) { cout << "One argument constructor this: " << th...
73,596,680
73,597,186
constraints with c++20 concepts
I'm trying to understand C++20 concepts, in particular the example from here. Why is it an error if we're templatizing f with a concept that's stricter than allowed? In other words doesn't Integral4 also satisfy the Integral concept? #include <type_traits> #include <concepts> template<typename T> concept Integral = st...
f takes a template template parameter that is constrained on Integral. This means that f is allowed to use any type T which satisfies Integral on this template. For example, short. S3 is a type constrained on Integral4, which subsumes Integral. This means that, while any type U which satisfies Integral4 will also satis...
73,597,452
73,598,005
How to include glm in opencl application?
I'm tyring to include glm as a data structure types for vec3,..etc but I can't include it, it always complain about other headers like cmath.h is not found err = clBuildProgram(program, 0, NULL, "-I C:\\Users\\xgame\\Desktop\\test\\opencl_raster\\external\\include\\glm", NULL, NULL); In kernel: #include "glm.hpp" C...
While #include "some_header.h" works in OpenCL C, you cannot include C++ headers. OpenCL C is based on C99, not C++; it does not support a lot of C++ functionality like classes. The good news is: OpenCL C already has cmath-like functionality and vector types built-in, for example the float3 vector type. No need to incl...
73,597,763
73,597,787
giving integer value to character data type in c++ and how ascii symbols (code >127) get printed?
When we perform the following code: char p = 0 ; cout << p << endl ; Does this mean that p stores the symbol whose ASCII code is 0? (Which is NULL Character, and therefore nothing gets printed?) The range of character data type is -128 to 127. And ASCII 0 to 256. So, how those ASCII symbols (code > 127) get printed? F...
Yes, 0 is ASCII NUL. char is signed on some platforms and unsigned on others. Standard ASCII only has a range of 0 to 127. The rest, whether they are 128 to 255 or -128 to -1, are sometimes called Extended ASCII and are less consistent across systems.
73,597,765
73,606,189
How to conditionally select base constructor in initialization list of derived constructor
Example: A wrapper for std::vector. I have 2 move constructors: template <class Allocator> class MyVector { .... MyVector(MyVector&&) = default; MyVector(MyVector&& other, const Allocator<int>& alloc) : vec(std::move(other.vec), alloc) {} private: std::vector<int, Allocator<int>> vec; ... } However, I w...
Thanks for the comments on the question. Summarizing them as an asnwer. It seems impossible to use condition to select base constructors. As a solution I removed the scoped allocator adaptor and just changed the code from MyVector v; v.emplace_back() to v.emplace_back(MyVector::value_type{v.get_allocator()}; thus effe...
73,597,814
73,597,995
What if declared variable in condition of if statement is not convertible to bool
The reference says in the syntax of if statement that: attr(optional) if constexpr(optional) ( init-statement(optional) condition ) statement-true ... condition - one of expression which is contextually convertible to bool declaration of a single non-array variable with a brace-or-equals initializer. But for th...
So my question is, is it just omitted as a consensus, or I missed something? From stmt.pre#4: The value of a condition that is an initialized declaration in a statement other than a switch statement is the value of the declared variable contextually converted to bool. (emphasis mine) This means that in the second c...
73,598,632
73,598,998
OpenGL glfwGetVideoMode causes seg fault
I have a simple program where I want to check the formatting of my GLFW window but glfwGetVideoMode causes a segfault. Here is my code: if (!glfwInit()) { VI_ERROR("Couldn't init GLFW\n"); exit(0); } glfwWindowHint(GLFW_SAMPLES, 6); window = glfwCreateWindow(gl...
The main problem is that glfwGetWindowMonitor returns null and thus glfwGetVideoMode results in a read from a nullptr. In GLFW, only fullscreen windows are associated with a monitor. Since you pass NULL as forth parameter to glCreateWindow and never call glfwSetWindowMonitor, the current window is in windowed mode and ...
73,599,376
73,628,952
lambda capture in C++17
[expr.prim.lambda.capture]/7: If an expression potentially references a local entity within a scope in which it is odr-usable, and the expression would be potentially evaluated if the effect of any enclosing typeid expressions ([expr.typeid]) were ignored, the entity is said to be implicitly captured by each interveni...
P0588R0 contains the rationale explaining why the rules for implicit capture were changed in order to capture some variables that are not going to be odr-used anyway. It's very subtle. Basically, in order to determine the size of a lambda closure type, you need to know which variables are captured and which ones are no...
73,599,458
73,600,189
C++ output of string.size() not correct
I wrote the following code: #include <iostream> #include <time.h> #include <string.h> int main() { std::string alphabet = "abcdefghijklmnopqrstuvwxyz"; std::string word; unsigned long long int i = 0; srand(time(NULL)); while(true) { int randomIndex = rand() % 27; word += alphab...
Let's change the print debug line as follows. std::cout << randomIndex << '\t' << i << " : " << word << " --> " << word.size() << std::endl; Here, when we check the strings that look like a single character but 2 characters, we come across them in a random number of 26. The length of the string "abcdefghijklmnopqrstu...
73,599,532
73,599,728
Is it legal for a lambda to odr-use this or a not captured entity with automatic storage duration in C++20?
[expr.prim.lambda.capture]/8 of the final draft of C++17 N4659: An entity is captured if it is captured explicitly or implicitly. An entity captured by a lambda-expression is odr-used in the scope containing the lambda-expression. If *this is captured by a local lambda expression, its nearest enclosing function shall ...
For future reference, I find this GitHub repository https://github.com/cplusplus/draft is useful in finding out how things changed between different C++ standards. In particular, I found this commit using git blame, which is the result of P0588R1: Simplifying implicit lambda capture (to resolve CWG 1632. Lambda capture...
73,599,692
73,599,736
exceeding range for signed char data type
If we are on a platform which supports unsigned char data type then, the char range is from 0 to 255. So, char c = 255 ; c++ ; cout << c ; // 0 gets stored to c, which corresponds to null character. But what if we are on a platform which supports signed char (-128 to 127) char d = 127 ; d++ ; cout << d ; // will it ge...
Signed integral types are always a ring of -2^b .. 2^b - 1 since C++20, where b is the number of bits. So, in your second example, if char is 8-bit, you'll likely have -128 [1]. I say 'likely', because technically signed integer overflow is still an UB and anything might happen, so that's one more reason not to depend ...
73,599,699
73,600,243
Create new instance of std::thread/std::jthread on every read call
I am developing a serial port program using boost::asio. In synchronous mode I create a thread every time read_sync function is called. All reading related operation are carried in this thread (implementation is in read_sync_impl function). On close_port or stop_read function reading operation is stopped. This stoppe...
You don't need to deal with the jthread's destructor. A thread object constructed without constructor arguments (default constructor), or one that has been joined, is in an empty state. This can act as a stand-in for your nullptr. class SerialPort { public : std::jthread thread_sync_read; ... SerialPort(.....
73,600,107
73,600,494
c++ make part of a header file visible to customers
My c++ software uses another repo that collects common classes/functions. Quite often, my software only uses one of a few related classes presented in one header file. Say the external repo has a file "data_types.h", with three classes. class X { // definition } class Y { // definition } class Z { // definition } My...
You need to split such headers into at least two, so that you can ship the necessary one without the unnecessary parts. If you cannot modify the headers, an alternative is to simply copy-paste the necessary part(s) into a new header, and keep using the original header internally when you build if you need other parts i...
73,600,228
73,600,480
Handling external C++ dependencies
The project structure we used to use was that code + prebuild external dependencies were source controlled in SVN. This was cumbersome because the external libraries were large and didn't need to be source controlled since they were prebuilt binaries. Now we have source in git and the prebuilt binaries are in the cloud...
Problem here is that if you make changes to lib then things will not build correctly until the developer goes and redownloads this lib folder. clear indication that the exact version you want to use is part of what you should track alongside your source code. I assume there's a way to cache it so it doesn't rebuild ...
73,600,283
73,600,387
How to concatenate LibTorch tensors created with a multi-thread process std::thread in C++?
A multi-thread process in C++ returns tensors and I want to concatenate them into one tensor in order. In C++ I have a single function which returns a single 1x8 tensor. I call this function multiple times simultaneously with std::thread and I want to concatenate the tensors it returns into one large tensor. For exampl...
Threads can't return tensors, but they can modify tensors via pointers. Try this (untested, may need a bit of tweaking): void get_tensors(torch::Tensor* out) { torch::Tensor one = torch::rand({8}); *out = one.unsqueeze(0); } int main() { std::thread ths[12]; std::vector<torch::Tensor> results(12); ...
73,600,478
73,600,582
Handling alignment in a custom memory pool
I'm trying to make a memory pool class that allows me to return pointers from within a char* array, and cast them as various pointer. Very very simplified implementation: class Mempool { char* mData=new char[1000]; int mCursor=0; template <typename vtype> vtype* New() { vtype* aResult...
alignof(std::max_align_t) will tell you the alignment required on your platform for standard functions like malloc(). You should use that if you don't know what alignment requirements the users of your allocator will have. Simply round sizeof(vtype) up to the nearest multiple of alignof(std::max_align_t) when you incr...
73,600,564
73,600,599
Input validation and a condition
I am having a hard time accepting the users input if they enter something < 60 on the first try. I want to make sure no letters are inputing hence the input validation but also less then a certain number. If the user enters 60 how can I get it to act on the first input? int score; cout << "Enter your te...
You can combine the logic of both your conditions into a single loop: int score; std::cout << "Enter your test score: "; // check if either extracting score failed or if score is less than 60: while(!(std::cin >> score) || score < 60) { if(std::cin) { // extraction succeeded but `score` was less than 60 st...
73,600,818
73,601,015
Indentation level management in C++ Logger class
I want to build a printer class that co-manages the indentation level automatically by an Indentation level destructor. However, this code uses a static indentation level, it works well for a single instance. What workaround I can make to make a unique indentation level across several instances? #include <stdio.h> #inc...
you capture the Logger instance to Indents. (and change Logger::indents to non-static) class Logger{ int indents = 0; // no more static public: struct Indents{ Indents (Logger& logger):logger(logger) { logger.indents++; }; Indents (const Indents&) = delete; ~Indents () { logger.indents--; ...
73,601,293
73,602,041
Thread-safe file updates
I need to learn how to update a file concurrently without blocking other threads. Let me explain how it should work, needs, and how I think it should be implemented, then I ask my questions: Here is how the worker works: Worker is multithreaded. There is one very large file (6 Terabyte). Each thread is updating part o...
Threads should not block other blocks (no lock on file, or minimum possible number of locks should be used) Your code sample uses fseek followed by fwrite. Without locking in-between those two, you have a race condition because another thread could jump in-between. There are three reasonable solutions: Use flockfile...
73,601,411
73,601,836
How to distribute C++20 modules?
All the literature about modules is quite recently new, and I am struggling with one core concept thing. When I make my own modules, after the linkage process, does exists a conventional or accepted way of package those modules to distribute them as a library?
Broadly speaking, the products of building a module's interface (as distinct from the linker-products of compilation, like a static/shared library) are not sharable between compilers. At least not the way that compiled libraries for the same OS/platform are. Compiled module formats are compiler-specific and may not eve...