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
70,650,522
70,650,615
how to guarantee initilization of a stack variable with a compile time constant
In C++20 we now have constinit. constexpr and consteval. I can now guarantee that a static variable is initialized by the result of a constexpr or consteval function by using constinit. OK I also can guarantee that a stack variable is initialized with the result of a consteval function executed in compile time. But how...
I think it is better to use consteval function, but if you cannot change it, you can simply use a temporary variable which will surely optimize later: constexpr int func( int i ) { return i+2; } int main() { constexpr int i1 = func(8); auto i2 = i1; i2 = 9; } Although you may not like this method, ...
70,651,203
70,652,275
how to set shared memory between python and c++ in linux and osx
I was able to share memory on windows simply using winapi in cpp and mmap.mmap in python. just match "name". And I was able to set the name of the shared memory using <boost/interprocess/shared_memory_object.hpp> on mac. But python's mmap.mmap() didn't work. Even in the official documentation the parameters were differ...
The issues is that shmget second parameters in in bits, not bytes. So the correct way to write the code is: shmid = shmget(777, 512 * 8, IPC_CREAT | 0666)
70,651,317
70,651,425
How can I create an array of void pointers through variadic templates?
I have something like: class A { public: A(B* b, int* i) { void* args[] = { (void*)&b, (void*)&i }; } }; But I need it to be more generic, in the sense that I want to the constructor of A to accept any number of variables, of any type. How do I accomplish this with templates?
You can write your constructor this way: class A { public: template <class... Args> A(Args*... pargs) { void* args[] = { (void*)&pargs... }; } }; Note that you are storing the address of the pointers, not the pointers themselves, in args. Also I wouldn't use that kind of things unless you have a ve...
70,651,696
70,651,803
Difference between ordinary parameter, reference parameter and const reference parameter passed by ordinary object and object created temporary
Since I'm a beginner in c++, some questions don't quite understand. This question came across by accident while I was reading C++ primer 5th. I have a Cat class with 3 different constructors(named by Constructor 1, Constructor 2, Constructor 3): class Cat { friend class Cats; private: std::string name; publi...
It's pretty simple: ctor 1 receives the argument by copy (pass by value); ctor 2 receives the argument by non-const lvalue reference, so it only supports non-const lvalues. ctor 3 receives argument by const lvalue reference so it supports const-lvalue, non-const lvalue, const rvalue and non-const rvalue. Instantiati...
70,651,941
70,652,946
Boost::Spirit doubles character when followed by a default value
I use boost::spirit to parse (a part) of a monomial like x, y, xy, x^2, x^3yz. I want to save the variables of the monomial into a map, which also stores the corresponding exponent. Therefore the grammar should also save the implicit exponent of 1 (so x stores as if it was written as x^1). start = +(potVar); potVar=(va...
I think I solved the original problem myself. The second try works. Indeed. It's how I'd do this (always match the AST with your parser expressions). However, I don't see how I doubled the variable name. It's due to backtracking with container attributes. They don't get rolled back. So the first branch parses potVa...
70,652,383
70,668,665
Freeze/Fail when using functional with OpenMP [Pybind11/OpenMP]
I have a problem with the functional feature of Pybind11 when I use it with a for-loop with OpenMP. I've done some research and my problem sounds pretty similar to the one in this Pull Request from 2 years ago, but although this PR is closed and the issue seems to be fixed I still have this issue. A code example I crea...
You're likely experiencing a deadlock between OpenMP's scheduler and Python's GIL (Global Interpreter Lock). I suggest attaching gdb to your process and looking at where the threads are to verify that's really the problem. IMHO mixing Python functions and OpenMP like that is asking for trouble. If you want multi-thread...
70,652,546
70,743,356
IncrediBuild configure build order
I have a solution with multiple projects in it. From those numerous projects some depend on the Libs projects and the test projects depend on the code, obviously. How do I configure IncrediBuild to build Libs first, then build code and only then proceed to building tests? I have: Microsoft Visual Studio Professional 2...
I opened Project -> Project Dependencies... went over every project and configured the code to depend on Libs and Tests to depend on the code projects and now they are built in the correct order and I don't have to go over every Lib and build/rebuid it every time I pull a minute change in it from the repository. In the...
70,652,769
70,660,313
Can multi-threading improve the performance definitely
I'm using C++11 to develop a project. In some function, I got some parallel tasks as below: void func() { auto res1 = task1(); auto res2 = task2(); auto res3 = task3(); ... std::cout << res1 + res2 + res3 + ...; } Well, each task is a little heavy, let's say each task would spend 300ms. Now I'm thi...
I'm not sure if the OS ensures that it will execute these threads immediately or it may need to wait for some other stuff? The OS will try to start up the threads as quickly as it can. They aren't guaranteed to already be running at the exact instant your thread object's constructor constructor returns, but OTOH the...
70,652,803
70,654,845
C++ dangling reference strange behaviour
int*& f(int*& x, int* y){ int** z = &y; *z = x; return *z; } Hello everyone, I've been given this code on an exam and I had some problems with it. My understanding is that given a reference to a pointer (x) and a pointer copy constructed (y) in the body of the function a local double pointer (z) is beeing created a...
Your test is not as sharp as it could be: In order to show that the reference is dangling you should actually store the reference and not a copy of the value of the deceased object it refers to. To understand why that would be more interesting let's dissect the function for a sec. int** z = &y; makes z point to y; *z ...
70,652,825
70,658,373
eBPF: raw_tracepoint arguments
I am getting into eBPF programming and want to use raw tracepoints, but I do not really understand, how to use them and how to access the arguments correctly. I would appreciate any help and hints to documantation. My questions: How do I get the arguments from the syscall by using a raw_tracepoint instead of a tracepo...
I think I worked it out, based on this article. The ctx of a raw_tracepoint program is struct bpf_raw_tracepoint_args. Which is defined in bpf.h as struct bpf_raw_tracepoint_args { __u64 args[0]; }; So basically just an array of numbers/pointers. The meaning of these arguments are depend on how the tracepoint prot...
70,653,013
70,653,212
Add the instance name to the constructor arguments as an std::string with Macros
More precisely, I have a class: struct S { template <class... T> S(std::string instance_name, T*... ptrs); } That needs to be constructed in a way like: STRUCT(example(arg1, arg2, arg3)); Where STRUCT is the macro that expands to: S example(std::string("example"), arg1, arg2, arg3); I have been trying with ...
Suggestion: #define STRUCT(inst,...) S inst(std::string(#inst),__VA_ARGS__) It would then be used slightly different from what you want: STRUCT(example, arg1, arg2, arg3); ... but it expands to exactly what you want: S example(std::string("example"), arg1, arg2, arg3); Demo
70,653,375
70,654,432
Conversion operator with const-result - GCC/Clang discrepancy
Given the following code snippet: struct Foo { }; struct Bar { operator const Foo() { return Foo(); } }; int main() { Bar bar; Foo foo(bar); return 0; } See here on godbolt It compiles fine with gcc 11.2 but fails to compile with clang 12.0 with the following error: <source>:12:13: error...
I think this is the open CWG issue 2077. Basically, Foo foo(bar); is direct-initialization, meaning that it will consider the constructors of Foo for overload resolution and choose the best viable one. The candidates are the implicit copy and move constructor with signatures Foo(const Foo&); Foo(Foo&&); If you look a...
70,653,670
70,654,777
Obtaining decoder MFT for H.264 video
i am trying to get a hardware decoder from media foundation. i know for sure my gpu supports nvdec hardware decoding. i found an example on github which gets the encoder, nvenc without any problem. but when i switch the params to decoder, i either get a bad hresult or a crash. i tried even getting a software decoder by...
There might be no dedicated decoder MFT for hardware decoding (even though some vendors supply those). Hardware video decoding, in contrast to encoding, is available via DXVA 2 API, and - in turn - is covered by Microsoft H264 Video Decoder MFT. This stock MFT is capable to decode using hardware and is also compatible ...
70,653,992
70,654,641
Generate a random prime using c++11 std::uniform_int_distribution
Trying to generate a random prime p in the range [2,2147483647] using the C++11 std::uniform_int_distribution. It's been commented that this approach might not be correct: It is not immediately obvious that this p is uniformly distributed over the set of all primes <= 2^31 - 1. Whatever uniformity and bias guarantees ...
The code you presented: Uniformly picks a random prime number in the range. Any given prime number in the range will have the same probability of coming up as any other prime in the range. will not produce numbers that are uniformly distributed around the range of integers. E.g. there will be much more numbers in the ...
70,654,064
70,657,188
Why does CppCheck flag static constexpr members as unusedStructMember, when it is used later in the struct definition
CppCheck is flagging the definition of BufLen as an unusedStructMember, even though it is used on the next line to define the length of the array. (style) struct member 'TxDetails_t::BufLen' is never used. [unusedStructMember] static struct TxDetails_t { static constexpr int32_t BufLen = 128; uint8_t b...
This is indeed a false positive and it is fixed in the upcoming Cppcheck 2.7. I can reproduce it with 2.6 but not with the latest head. Looking at the list of fixed issues it appears you encountered https://trac.cppcheck.net/ticket/10485.
70,654,703
70,664,957
Passing a c# array of object to COM interface method
I should pass a pointer of object array to a COM interface with the following IDL and C++ definitions: C++ code: UpdateItem( LONG lID, LONG lNumOfFields, FieldIdEnum* pFields, VARIANT* pvValues ) IDL: HRESULT UpdateItem( [in] LONG lID, [in] LONG lNumOfFields, [in, size_is(lNumOfFields)] FieldIdEnum* pFields, [in, size...
I have found the solution. I have redefined the interface method: void UpdateItem([In] int lID, [In] int lNumOfFields, [In] ref FieldIdEnum pFields, [In][MarshalAs(UnmanagedType.LPArray)] object[] pvValues); ... and call this as: FieldIdEnum[] updateFieldIDs = { FieldIdEnum.fi1ID, FieldIdEnum.fi2At...
70,654,795
70,655,355
Why doesn't C++ automatically throw an exception on arithmetic overflow?
The C++ Standard at some point states that: 5 Expressions [expr] ... If during the evaluation of an expression, the result is not mathematically defined or not in the range of representable values for its type, the behavior is undefined. [ Note: most existing implementations of C++ ignore integer overflows...] I'm tr...
If that's the case, can't the underlying arithmetic processing hardware be used to do that check for free? Raising an exception always has a cost. But perhaps some architectures can guarantee that when an exception is not raised, then the check is free. However, C++ is designed to be efficiently implementable on a wi...
70,654,850
70,655,222
Big Integer Class C++
I'd like to write an unsigned Big Int library in C++ as an exercise, however I would like to stay away from using the traditional vector of chars storing individual digits. Due to the amount of memory wasted by this approach. Would using a vector of unsigned short ints (ie. 16 bit postive integers) work, or is there a ...
Storing digits in corresponding chars is certainly not traditional, because of the reason you stated - it wastes memory. Using N-bit integers to store N corresponding bits is the usual approach. It wastes no memory, and is actually easier to implement (though harder to debug, because the integers are typically large). ...
70,655,605
70,655,966
Is there any performance benefit capturing only needed variables in scope in a lambda expression with [&var] instead of capturing all with [&]?
Or does it make any difference at all, because unused references are optimized away by the compiler? "When a lambda definition is executed, for each variable that the lambda captures, a clone of that variable is made (with an identical name) inside the lambda. These cloned variables are initialized from the outer scop...
The way the compilers I am familiar with implement closures is to effectively create a struct of all the captures and pass a pointer to the struct as a parameter to the function. The compiler will only add to the struct those captures explicitly listed, and in the case of the general capture, only those visible variabl...
70,655,695
70,657,229
How to define struct field type in Metal Shading Language?
It is not clear how to define ref or ptr type of struct field? struct uint128_t { uint64_t lo; uint64_t hi; device uint64_t& operator[](int i) { return (i == 0) ? lo : hi; } ... } Reference to type 'device uint64_t' (aka 'device unsigned long') could not bind to an lvalue of type 'uin...
You need to specify an address space for the function itself. Otherwise, you can't use address-space specific stuff. Here's the right definition: struct uint128_t { uint64_t lo; uint64_t hi; device uint64_t& operator[](int i) device { return (i == 0) ? lo : hi; } };
70,655,807
70,656,214
Program compiles, but cannot run because of missing library that exists
I have an OpenGL program. I have all the include directories, and everything. Directory Structure: Main.cpp Lib/ GL/ GLEW/ glm/ I compile the program by running: g++ main.cpp -lGL -lm -lX11 -lpthread -lXi -lXrandr -ldl -I. -lglfw -Llib/ -o main -lGLEW The error is on -lGLEW. The program compiles with no errors, but w...
When running a dynamic linked executable, the linker must be able to find all the libraries it needs. It always searches a list of fixed default paths like /lib and /usr/lib additional paths defined by the environment variable LD_LIBRARY_PATH any non-standard paths hard-coded in the binary by the -Wl,-rpath g++ option...
70,655,977
70,656,381
C++ map with adjacent_difference
Really confused by some errors I'm getting related to using a std::map container with a call to std::adjacent_difference. The documentation for adjacent_difference says the following about defining a custom operator: op - binary operation function object that will be applied. The signature of the function should ...
Studying the cppreference link you provided shows that std::adjacent_difference() cannot transform its output to a type different from the input: both acc (the accumulated value) and the result of val - acc or op(val, ACC) <...> must be writable to OutputIt. So, to use algorithms, you would first need to use std::tra...
70,657,424
70,657,492
What is meant by a "Relative Comparison" and an "Absolute Comparison"?
Quoting from this article: REAL NUMBERS Binary search can also be used on monotonic functions whose domain is the set of real numbers. Implementing binary search on reals is usually easier than on integers, because you don’t need to watch out for how to move bounds: binary_search(lo, hi, p): while we choose not to t...
The last paragraph explains the issue with using the absolute difference: If you need to do as few iterations as possible, you can terminate when the interval gets small, but try to do a relative comparison of the bounds, not just an absolute one. The reason for this is that doubles can never give you more than 15 dec...
70,657,844
70,668,801
Using 3rd Party Shared Object Library and header files in CMake
I am trying to use this ZED Open Capture library for using the ZED Mini camera for my project on RaspberryPi. I succesfully installed the library and the shared object file is at /usr/local/lib/libzed_open_capture.so and the include headers are at the location /usr/local/include/zed-open-capture/. To include this libra...
videocapture.hpp wraps the definitions you need inside #ifdef VIDEO_MOD_AVAILABLE. It seems likely that this is not defined. The root CMakeLists.txt in the ZED package defaults BUILD_VIDEO to ON, so this was likely all defined for the package build. But as others have pointed out, the package does not persist this i...
70,658,037
70,658,859
Problem understanding the behaviour of std::map try_emplace for a composite key
I have a std::map<CompositeKey, std::string>, where CompositeKey is a class I wrote. This CompositeKey has three int data members, all the constructors, all the copy assignment operators and a friend bool operator<, which compares the sum of the three data members. I understood how to use emplace and emplace_hint. For ...
I think you may be misunderstanding the cppreference documentation. In your code, you are always trying to add a key that is not in the map. And you are passing that key as an lvalue reference. The only difference with your two cases is that you are using a hint in the second call. So the two try_emplace versions you a...
70,658,493
70,658,773
Program not showing the values inserted in a binary search tree
I have tried writing a code to implement a binary search tree, however when I run my code outputs nothing and closes a program. I think my insert function is correct since I wrote cout<<"yes" at multiple places in the insert function, and to show all the nodes of the binary search tree I have used in order traversal wh...
For starters the function insert can produce a memory leak when a value is added to the tree when there is already a node with the same value because in this case only this else statement can be evaluated while (current != NULL) { //... else { current = current->left; } } So the loop will end i...
70,658,717
70,659,283
How do I sort a vector of pairs by both of the values rather than just the second one?
What I am looking to do is sort a vector of pairs in a way where the first value is lowest to greatest and the second being greatest to lowest and having priority over the first value ordering whilst keeping them together. For example, let's say I had this code: #include <iostream> #include <vector> using namespace st...
The simplest way is to use the standard functions std::sort() and std::tie(). Here is a demonstration program: #include <iostream> #include <utility> #include <vector> #include <iterator> #include <algorithm> int main() { std::vector<std::pair<int, double>> v = { { 2, 2.4 }, { 9, 3.0 }, ...
70,658,753
70,660,089
Iterating vector-based priority_queue
I need to iterate over std::vector-based priority_queue. As many answers here suggest, I can inherit from priority_queue and access underlying container (std::vector in my case). Is it guaranteed that priority_queue elements are stored starting from element 0 of the underlying vector and that vector size equals queue s...
In short, yes. The standard [priqueue.members] defines the operators on a priority queue in terms of push/emplace/pop_back and heap operations. It is trivial to see that the size of the underlying container will be equal to the size of the priority queue, and that elements will be stored starting from the beginning of ...
70,659,217
70,659,632
Exactly which parts of the standard require this breaking change involving operator <?
A change was made in C++20, and I'm having a hard time finding where in the standard I can go look to learn that this change happened. Would someone please quote me the section of the standard that tells me this will happen? I am aware of this question: Breaking change in std::tuple lexicographic comparison in C++20 wi...
In C++17, [pairs.spec] defined all the relational operators. For instance, operator< was specified as: template <class T1, class T2> constexpr bool operator<(const pair<T1, T2>& x, const pair<T1, T2>& y); Returns: x.first < y.first || (!(y.first < x.first) && x.second < y.second). In C++20, with the adoption of <=>,...
70,659,577
70,659,908
How to find a substring in only a portion of a std::string?
I have a std::string and i want to be able to find text only in a section of it : so i need to specify a start and an end position. In std::string::find() one can only specify the start position. I am trying to find the best way to search only in a portion of haystack. That would consist of giving an end_pos to stop th...
std::string does not have a method that suits your requirement to search a sub-range of the haystack string. Have a look at std::search() for that instead, eg: std::string needle = ...; std::string::iterator end_iter = haystack.begin() + end_pos; std::string::iterator found_iter = std::search(haystack.begin() + start_...
70,659,585
70,661,299
Avoiding undefined behaviour: passing a temporary to a `std::function` which has a const ref member variable
The following example is a simplified version found in production code #include <string> #include <functional> #include <iostream> #include <vector> struct A { std::string myString = "World"; }; struct B { void operator()() { std::cout << a.myString; } const A& a; }; std::vector<std::fun...
This example has no undefined behavior. Calling Store copy-initializes the argument of type std::function<void()> from the temporary object of type B. In doing so, std::function uses perfect forwarding to initialize its own internal object of type B, which is therefore move-constructed from the original temporary. The ...
70,659,634
70,659,957
Why writing reverse iterator can affect whether an iterator is random-access-iterator or not?
I wanna write a container with random-access-iterator: #include <cstddef> #include <iterator> #include <concepts> namespace foo { struct container { struct iter { using difference_type = std::ptrdiff_t; using pointer = int*; using reference = int&; ...
The mystery here is why adding a few lines of code that don't alter the definition of foo::container::iter causes the static_assert to fail. This is because the implementation of std::reverse_iterator's constructor, in the body of the commented function, evaluates concept std::random_access_iterator to determine what s...
70,659,635
70,660,299
Numerical implementation of n-th derivative of f(x)?
I implemented a C++ code to numerically solve the n-th derivative of a function in a point x_0: double n_derivative( double ( *f )( double ), double x_0, int n ) { if( n == 0 ) return f( x_0 ); else { const double h = pow( __DBL_EPSILON__, 1/3 ); double x_1 = x_0 - h; double x_2 = x_0 + h; doub...
It is not a good implementation At least these problems. Integer math Use FP math as 1/3 is zero. 1/3 --> 1.0/3 Using the cube root optimal for n==1 But not certainly other n. @Eugene Wrong epsilon Below code is only useful for |x_0| about 1.0. When x_0 is large, x_0 - h may equal x_0. When x_0 is small, x_0 - h may...
70,659,662
70,683,799
Visual Studio 2019 C++ project error "A dependent dll was not found", how to know which dll is not found
I found several others are puzzled by this matter as well, but no answer is satisfying. I am inheriting a big C++ program set up in Visual Studio 2019, it builds fine, but when running it, the studio complains "A dependent dll was not found" without any other useful info. Is there anyway to know which dll is needed, or...
Using Dependency Walker, I have identified the missing DLL. It does not require installation, very good to use.
70,660,208
70,660,246
Access from multiple source files to one struct array
I tried to upgrade my "working code" with a new function. For this I tried to outsource some functionality into separate files. At the moment I'm not sure what to do and I can't find a solution for the problem. The code below is only a little part of the code, but I hope it is enough to explain what is going wrong. I n...
The struct's layout has to be included in the header file. struct ResultFieldColor { byte resultHue = 0; byte resultSaturation = 0; byte resultBrightness = 0; }; You may have heard people say not to do this. What they meant was that function implementations shouldn't be in the header, so if you have a function f...
70,660,488
70,673,863
why are RTLD_DEEPBIND and RTLD_LOCAL not preventing collision of static class member symbol
I am trying to write a simple plugin system for an application and would like to prevent plugins from stomping on each others symbols, however RTLD_DEEPBIND and RTLD_LOCAL don't seem to be enough when it comes to static class members when they happen to have the same name in different plugins. I wrote a stripped down e...
gcc implements static inline data members (and also static data members of class templates, inline or not, and static variables in inline functions, and perhaps other things as well) as global unique symbols (a GNU extension to the ELF format). There is only one such symbol with a given name per process, by design. cla...
70,660,622
70,663,950
Am I using isalpha() function in c++ correctly?
I am working on a program that has a registry system where you can register new members. To give some context, the name you register has to be different than existing names, can only be one word, and is turned into all caps before being saved to a file. To avoid potential mistakes in file handling, I only want the user...
The main problem is that you use C-Style char[] for strings. In C++, we use the datatype std::string for strings. std::string is that superior compared to-Style strings, that it is hard to understand, why anybody wants still to use the old stuff. As a consequence you have the problems that you are facing now. You are u...
70,660,624
70,661,537
How to mark a variable as initialized at the language level?
I am using a linked C-library to get values into a variable. void f_wrapper(int& v){ auto s = f_legacy(&v); if(s != success) throw std::runtime_error{}; } ... int value; // clang-tidy complains here: using "variable 'value' is not initialized" f_wrapper(value); However, clang-tidy complains here: using "v...
It's not what you want to hear, but there's really only one way to initialize a variable "at the language level" in standard C++ -- and that's to initialize it. It really is that straight-forward. You're basically stuck with either this, or NOLINTing it, as you've already described in your question. It's not a glamorou...
70,660,641
70,660,785
clang vs gcc - CTAD of struct deriving from template parameter
Consider the following code: template <typename B> struct D : B { }; D d{[]{ }}; gcc 12.x accepts it and deduces d to be D</* type of lambda */> as expected. clang 14.x rejects it with the following error: <source>:4:3: error: no viable constructor or deduction guide for deduction of template argum...
In the code snippet, no deduction guide has been provided. P1816 added deduction guides for aggregate class templates in C++20, by requiring that an aggregate deduction candidate is generated. The code is valid, but Clang just doesn't support P1816 yet. Adding a deduction guide allows this to compile in Clang as well. ...
70,660,833
70,661,109
cannot interprete exported function and class from another project within solution?
I have ClassB of ProjectB rely on what is defined in ProjectA. ProjectA is built as a .lib as shown below ProjectB is just a exe. Below is the code. #pragma once #include "../../ProjectA/ClassA.h" class ClassB { public: void callClassB(); }; #include "ClassB.h" void ClassB::callClassB() { //ClassA::print_m...
I suggest you read this document carefully, it will help you. Regarding your question, you need to select the Configuration Properties > C/C++ > General property page. In the Additional Include Directories property, specify the path of the library directory. Then the program can run using my code in ClassB.cpp. #inclu...
70,660,993
70,742,911
Can't compile c++ program using gcc on Mac after updating to Monterey
*Update: Regarding the similar question macos-wchar-h-file-not-found, the command line tool switch(xcode-select --install) doesn't exist anymore. I am running on macOS Monterey system and I am trying to compile a simple hello world .cpp file using the g++-11 commend (I installed gcc using homebrew), I am getting the fo...
I also had the same problem and in my case the problem was outdated command line developer tools. I found out it by running $ brew doctor ... Warning: Your Command Line Tools are too outdated. Update them from Software Update in System Preferences or run: softwareupdate --all --install --force If that doesn't show y...
70,661,070
70,661,272
Can vector cause false sharing
I'm working with C++11 on a project and here is a function: void task1(int* res) { *res = 1; } void task2(int* res) { *res = 2; } void func() { std::vector<int> res(2, 0); // {0, 0} std::thread t1(task1, &res[0]); std::thread t2(task2, &res[1]); t1.join(); t2.join(); return res[0] + re...
can std::vector cause false sharing? Containers aren't something that "cause" false sharing. It's writing to objects that may cause false sharing. Specifically, writing in one thread to an object that is in the same "cache line" as another object that is accessed in another thread causes false sharing. Elements of an...
70,661,636
70,673,278
Operator= slowing down simulation
I am running a Monte Carlo simulation of a polymer. The entire configuration of the current state of the system is given by the object called Grid. This is my definition of Grid: class Grid{ public: std::vector <Polymer> PolymersInGrid; // all the polymers in the grid int x; ...
One thing that you can certainly do to improve performance is to force moving _G rather than coping it to G: G = std::move(G_); After all, at this stage you don't need G_ any more. Side remark. The fact that you don't need to copy all member data in operator= indicates that your design of Grid is far from perfect, bu...
70,662,470
70,662,604
C++ freeing memory of nested container and objects
There a great chance this question is duplicated, but I wasn't sure how to do a proper search on this. Also it may be trivial to you but it will help me as a beginner a lot! Say I have three classes, each has a container class A { std::map<int, B> container1; }; class B { std::unordered_map<int, C> container2;...
The short answer: Yes, all nested containers in this scenario will have their memory freed. The long answer: Let's work from the top. First, I'm going to assume that these are structs instead of classes (or that the containers have been declared public); otherwise, a.container1.clear() won't compile, as container1 woul...
70,662,970
70,663,247
Why is my answer off for certain values of binary representation provided?
The question basically asks us to convert the input binary string (only 1 and 0 provided). Input format is as follows (each separate point is a new line): Number of test cases 2N lines with: Length of binary string, Binary string on each alternative line Output is to return the decimal conversion of the string. My co...
runs correct for all smaller values of binary input (of length maybe less than 50). num += (digit-'0')*pow(2,len); is like num = num + (digit-'0')*pow(2,len); and the addition is done using double math with its 53-ish bit precision infected by pow(). Instead only use integer math: unsigned long long num = 0; ... n...
70,663,087
70,663,265
What is the meaning of Eigen's .resize(rows,cols) Matrix const MatrixXd as 'this' argument discards qualifiers error
When the Matrix argument is defined as constant I get .resize(rows,cols) Matrix const MatrixXd as 'this' argument discards qualifiers error void (const Eigen::MatrixXd &X){ X.resize(cols, rows) } returns an error but this works as expected: void(Eigen::MatrixXd &X){ X.resize(cols, rows)} I'm not too...
The warning means that the resize function that you called is not const qualified. The lack of const qualification means that the function cannot be called on a const lvalue. resize is a function that modifies the object. The rough meaning of "const" is that modification isn't allowed. X is an lvalue reference to const...
70,663,344
70,667,268
Qt5 make a copy of ini file(QSettings) to build folder using CMake
I'm Qt5 beginner. I saved two .ini file with QSettings for two different layout of toolbars and dockwidgets. coolUI.ini and fantacyUI.ini I move them to my project folder and want to copy them to the build/release folder when building with CMake. And then I can reset to one of them anytime in my app. If any information...
Assuming your coolUI.ini file is in a project directory/subdirectory that contains a CMakeLists.txt file you may try to use file(COPY_FILE ${CMAKE_CURRENT_SOURCE_DIR}/coolUI.ini ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/coolUI.ini) or file(COPY ${CMAKE_CURRENT_SOURCE_DIR}/coolUI.ini DESTINATION ${CMAKE_RUNTIME_OUTPUT_DIRECTOR...
70,663,430
70,663,550
Why does declaring a 2D array of sufficient size cause a segfault on Linux but not macOS?
Problem I'm trying to declare a large 2D Array (a.k.a. matrix) in C / C++, but it's crashing with segfault only on Linux. The Linux system has much more RAM installed than the macOS laptop, yet it only crashes on the Linux system. My question is: Why does this crash only on Linux, but not macOS? Here is a small progr...
Although ISO C++ does not support variable-length arrays, you seem to be using a compiler which supports them as an extension. In the line int Matrix2D[n][n]; n can have a value up to 2000. This means that the 2D array can have 2000*2000 elements, which equals 4 million. Every element has a size of sizeof(int), which ...
70,663,669
70,663,725
How to play with spdlog?
I downloaded and followed the example 1. Moved to example 2 (Create stdout/stderr logger object) and got stuck. Actually I can run it as it is but if I change spdlog::get("console") to spdlog::get("err_logger") it crashes. Am I supposed to change it like that? #include "spdlog/spdlog.h" #include "spdlog/sinks/stdout_co...
Because you need to register err_logger logger first. There is no default err_logger as far as I know. spdlog::get() returns logger based on its registered name, not variable. You need a code like this. Code is complex and you may not need all of it though: #include "spdlog/sinks/stdout_color_sinks.h" #include "spdlog/...
70,663,796
70,678,951
yocto image with boost 1.77: libboost_atomic.so is not on image, but is in sdk
I have an aarch64 based yocto image, and it contains also an app that I compile as a package and that app uses and links with boost 1.77 and uses boost::filesystem using cmake. The app on the image works and everything is ok. The problem I have is: I also generated the SDK part for yocto, and that SDK contains all boos...
I found the problem: for the SDK, I use a cmake toolchain file, and so that file did not contain a linker option that yocto uses: -Wl,--as-needed So using that option, the linker is not linking to libboost_atomic.so anymore and I can run my sdk-compiled version on the image!
70,663,939
70,664,103
function CIN gets skipped every time
I wanted to make a small "game" with a little bit of story, but I did some code and I think i did some major mistakes, here's the code int main() { char o, z, q, r; string f, w = "yes", e = "no"; cout << "Hello, summoner!" << endl; cin >> o; cout << "You know why you are here, right?" << endl; cin >> q; switch ( z )...
It may not get skipped. You may be entering more than one characters in 'o', which is not allowed in your case and the second character automatically is stored in variable q. Try changing the data type of the variables mentioned if you want to enter longer strings in the variables.
70,664,043
70,666,252
Clip Raster with Polygon with GDAL C++
I am trying to clip a raster using a polygon an GDAL. At the moment i get an error that there is a read access violation when initializing the WarpOperation. I can access my Shapefile and check the num of features so the access is fine i think. Also i can access my Raster Data (GetProjectionRef).. All files are in the ...
Your psWarpOptions->hCutline should be a polygon, not a layer. Also the cutline should be in source pixel/line coordinates. Check TransformCutlineToSource from gdalwarp_lib.cpp, you can probably simply get the code from there. This particular GDAL operation, when called from C++, is so full of pitfalls - and there are ...
70,664,220
70,664,244
C++: Passing object to class constructor, how is it stored?
Consider the following example of a simple class implementation in C++. foo.hpp #include <vector> class Foo { private: std::vector<double> X; public: Foo() = default; ~Foo() = default; Foo(std::vector<double>&); }; foo.cpp #include "Foo.hpp" Foo::Foo(std::vector<double>& X): X(X) {} In this ca...
Yes, the data member X will be copy-initialized from the constructor parameter X. If you declare the data member X as reference, then no copy operation happens. E.g. class Foo { private: std::vector<double>& X; public: ~Foo() = default; Foo(std::vector<double>&); }; Foo::Foo(std::vector<double>& X): ...
70,664,337
70,664,538
Run all catch2 tests in one compile unit without tag definition
I have the following project structure: test_main.cc #define CATCH_CONFIG_MAIN #include "catch2.hpp" test1.cc #include "catch2.hpp" TEST_CASE("test1", "[test1]") { REQUIRE(1 == 1); } test2.cc #include "catch2.hpp" TEST_CASE("test2", "[test2]") { REQUIRE(2 == 2); } Now, I can run all tests with e.g. test1 usin...
I've found in documentation this: Catch2/command-line.md at devel · catchorg/Catch2 · GitHub Filenames as tags -#, --filenames-as-tags When this option is used then every test is given an additional tag which is formed of the unqualified filename it is found in, with any extension stripped, prefixed with the # charact...
70,664,433
70,665,261
Why is it not possible to add a `std::chrono::hours` to a `std::chrono::sys_days`
Taking the first steps with <chrono> library, I'm starting with basic arithmetic on a days grained time_point. Thanks to a very useful post by @HowardHinnant, I managed to write this: #include <chrono> using namespace std::chrono_literals; int main() { std::chrono::sys_days d {std::chrono::January/31/2022}; d ...
You can add hours to days. What you can't do is implicitly convert that into days again. You need a cast d = std::chrono::time_point_cast<std::chrono::days>(d + 48h);
70,664,691
70,667,383
Problem with the Tool Flags during the c++ module compilation
I'm trying to compile the module in Eclipse and generate the additional output disassembles I've added these Tool Flags -fverbose-asm -Wa,-adhln -save-temps=obj > %OutFile%.asm But I receive this error clang: error: unsupported argument '-adhln' to option 'Wa,' Does anybody had a similar issue? If so please help Many...
OK so the target was to generate the assemblies with the instructions HEX and relative addresses I was not able to do that using Eclipse >> Tool Flags so I simply left one flag: -save-temps=obj Which generates AT&T systax assemblies but without details like (instruction Hex or relative address) But I've managed to gen...
70,664,812
70,664,979
Deduce the array-sizes in a variadic template function
I try to write a constexpr function that accepts a variable number of C-Strings. And I want to deduce all of the sizes (here: L0 and LL) of the passed arrays. Looks like a stupid error I make there, but trying to do so, I get an error: error: parameter packs not expanded with '...': 204 | constexpr auto generate(cons...
The problem should be the expansion of ss (that is variadic too) // ellipsis here ...........................................VVV constexpr auto generate(const char (&s0)[L0], const char (& ... ss)[LL]) {
70,665,163
70,673,666
Caret position in EditBox after change in text length
I have an EditBox in a MFC-dialog. The user is supposed to enter a number. I'm trying to automatically add separators to the number while the user is inputting it: When the number is more than 3 digits long, a separator is added between the hundreds and the thousands digit; a second one between the hundredthousands and...
It is unclear how you are handling "/ Adding/Removing of separators as needed". SetSel with the first parameter set to -1 will position the caret at the beginning of the string if the string changes after calling UpdateData(false) Create CString type of the variable (m_csEdit for example) for this edit control and ...
70,665,319
70,665,454
Program only prints out the first two lines of my code, and ignores the rest entirely
So the problem I am facing here is that, the program runs only the first two lines of the code and entirely ignores the rest. I have tried rewriting it, I have also searched the internet for solution, but I found nothing and the problem continues to persist. #include <iostream> using namespace std; struct customer{ ...
Your p variable has not been initialized yet: struct customer *p; That means it does not point to an instantiated object of type customer. So this is how you can create an object on the heap: std::unique_ptr<customer> ptr { std::make_unique<customer>{ } }; ptr will handle the deletion of the customer object for you. ...
70,665,558
70,666,939
How To Access Dynamically Created Buttons Click events Qt C++
I Created buttons dynamically for data from the database QPushButton *btnComment = new QPushButton("Comment"); btnComment->setProperty("id",qry.value(0).toString()); Is the button that i created dynamically I set a connect connect(btnComment, &QPushButton::clicked, this, &Planner::commentButton); and c...
As mentioned in the comment you can connect to a lambda rather than directly to a non-static member. Change the signature/definition of Planner::commentButton to... void Planner::commentButton (QPushButton *button) { /* * Use button accordingly. */ } Then simply change your connect call to... connec...
70,665,994
70,667,565
How to extract tuple into a function parameters
I'm working with C++ on Linux and I need to develop a common library to simplify the multi-threading development. Well, I know that there are some mechanism of multi-threading in C++11, such as std::async, std::future etc. But I have to work with pthread because of some historical reason. Basically, what I'm trying to ...
As mentioned in the comments, std::apply is suitable for your case. pthread_create( &td, nullptr, [](void* p) { auto param = static_cast<typename signature<decltype(f)>::argument_type*>(p); std::apply([](auto& f, auto&&... args) { f(std::forward<decltype(args)>(args)...); }, *param); return ...
70,666,090
70,666,144
How do I call an object of a class that inherits another class that has arguments in its constructor?
I am working with multiple classes and files, so I have created this dummy code to better define my problem. I have a parent class Parent and a child class Child. I've separated both of these in a .h and a .cpp file parent.h class Parent { Parent(int a, int b, int c); protected: void somefunc(); ...
How do I get rid of this error? You can solve this error by adding the default constructor in class Parent as shown below. Also, note that you need to make the constrcutors public. parent.h class Parent { public: //ADDED PUBLIC KEYWORD Parent(int a, int b, int c); //ADD DEFAULT CONSTRCUTOR P...
70,666,139
70,666,177
What happens when opeator= returns void rather than T&?
In operator overloading, the assignment operator is normally defined as follows: T& T::operator =(const T2& b); which returns T& as result. But I want to know what happens when we return void. For example, the assignment operator of std::atmoic<std::shared_ptr<T>> returns void: void operator=( std::shared_ptr<T> desir...
You won't be able to chain assignments a = b = c; (Nor introduce more complicated cases, like (a = b).method(); or if((a = b));.) OTOH, with void return type you don't need the ubiquitous return *this; boilerplate.
70,666,224
70,666,848
convert a text to another text with another structure
I just want to write an code to change the input to another text with another structure. for example a text is given. and I should convert them intoanother text like I say below. this is the input : typedef enum { RED, GREEN, BLUE } Color; and this should be the output : enum class Color { RED = 0, ...
#include <iostream> #include <string> #include <vector> using namespace std; int main() { string temp; vector <string> lines; while(true){ getline(cin,temp); lines.push_back(temp); if(temp.back()==';') break; } cout<<"enum class "<<lines.back().substr(2,lines.b...
70,666,773
70,667,123
Why is shared_ptr implemented using control block and not a static map?
To me, it looks like an implementation of std::shared_ptr which stores a reference counter in a static std::unordered_map<void*, struct Counters> would be much more simpler and also allow us to avoid some dirty workarounds like std::enable_shared_from_this (because std::shared_ptr<T>{this} wouldn't create new control b...
So why does a committee decided to stick with a control block implementation? It doesn't. The committee writes requirements that implementers must follow. They do not specify that std::shared_ptr be implemented in any particular way, so long as that way meets the requirements. Having said that, your proposed static s...
70,666,930
70,667,061
Taylor expansion in C++: function factory?
In some application I need to have access to the elements of some polynomial expansion (for example x^i for i = 0,1,...). My idea was to create a "function factory" like #include <functional> #include <iostream> std::function<double(double)> Taylor(unsigned int i) { return [i](double y) {return std::pow(y, i);}; }...
C++, long before lambdas were added to it, has always had a solution for this: Just implement a class with an operator(), so that instances become callables, i.e. useful as functions. We call such objects functors. #include <iostream> #include <memory> #include <vector> // Just an interface base class – not strictly ne...
70,667,492
70,667,798
Obtain using definition from templated class
Given the following classes: // Some random class class A { }; // A templated class with a using value in it. template<class TYPE_B> class B { public: using TYPE = TYPE_B; }; Next we use these two classes in class C. But if we are using B as the template parameter we would like to obtain the TYPE defined in it...
You have two issues in your code: You are missing a typename before TYPE_C::TYPE. Since TYPE_C::TYPE is a dependent name, you need to use typename to tell the compiler that you are looking for a type. You cannot use TYPE_C::TYPE ins the std::conditional1 expression because when TYPE_C is not B<>, that expression is i...
70,667,513
70,667,652
CMAKE_CXX_STANDARD vs target_compile_features?
I'm itching to upgrade our project to C++20. My CMakeLists.txt files generally say set (CMAKE_CXX_STANDARD 17) set (CMAKE_CXX_STANDARD_REQUIRED ON) but I get the sense that's not the Right Way to do it. What is the Right Way? Is it this?: target_compile_features(Foo PUBLIC cxx_std_20) where Foo is the name of my targ...
The newer alternative is definitely target_compile_features(Foo PUBLIC cxx_std_20) And with this you can and should remove the old set(CMAKE_CXX_STANDARD*). However the new version has an issue if you also want to disable compiler extensions with set(CMAKE_CXX_EXTENSIONS OFF). Its not possible with the new syntax as f...
70,667,719
70,667,834
Console couts a memory address instead of string
As I understand that strings can be treated like arrays, so I tried to insert each character of a string by iterating with a while loop. However the final cout pointed to a memory address, not the string I hoped it would print. int main() { int i = 0; int n = 2; char input; string str1[n]; whil...
When people say that strings are like arrays, they mean specifically "c-strings", which are just char arrays (char*, or char []). std::string is a separate C++ class, and is not like an array. See this question for a definition of C-strings. In your example, str1 is actually an array of std::strings, and when you print...
70,667,811
70,669,434
I/O Completion ports C++ And Threadpools
I'm trying to understand which is true, i read in multiple sources that IOCPs can be used to implement a threadpool, i'm using multiple IOCPs each in it's thread to do interprocess communication and i'm trying to reimplement my code to use just one IOCP and a threadpool to manage all my processes. can i use just one th...
does the IOCP has it's own internal threadpool ? no. if you create IOCP ( KQUEUE) by self - you need by self call GetQueuedCompletionStatus[Ex] (ZwRemoveIoCompletion[Ex] ). from which thread(s) - completelly your task.so here you need yourself create some "thread pool" which will be pop packets from IOCP and handle i...
70,667,971
70,676,906
Configuring Visual Studio 2019 to automatically pick up the highlighted option from intellisense in C++ by hitting enter
The intro text says it all. I tried messing around with options related with the intellisense on VS, but no success. I mean, it does pick our options via enter, but, by the default, we gotta confirm the selection with the arrow keys first, which is an unnecessary step. Any clues?
To implement your idea, you need to set Member List Commit Aggressive to true. The specific path is Tools->Options->Text Editor->C/C++->Advanced->Member List Commit Aggressive.
70,668,318
70,668,445
Why does this code compile with MSVC, but not in GCC or Clang?
And how to fix the code? Here is the code: https://godbolt.org/z/vcP6WKvG5 #include <memory> #include <utility> enum class Format { Number, Text, }; template <template <Format> typename Visitor, typename... Args> void switchByFormat(Format format, Args&&... args) { switch(format) { case Format...
Since Visitor is a template class rather than a type, you need to specify the template keyword switchByFormat<AstNodeFactory<AstNodeT, Args...>::template Visitor>( //^^^^^^^^ format, result, std::forward<Args>(args)...); Demo.
70,669,183
70,671,583
OpenCV returns no error when open is called, but gstreamer does
I have the problem when I open a camera with GStreamer, and the camera is not connected, I don't get an error code back from OpenCV. GStreamer returns an error in the console. When I check if the camera is open with .isOpend() the return value is true. When the camera is connected, it works without any issue. std::s...
This may just be because of a typo. nvarguscamerasrc has no property sensor_id but has sensor-id. It should work after fixing this. In not working case, cap.read() should return false.
70,669,886
70,679,371
trying to convert functions to c++ how do I change target to scene component
grapplecomponent.h protected: virtual void BeginPlay() override; UPROPERTY(EditAnywhere, BlueprintReadWrite) bool m_hooked; UPROPERTY(EditAnywhere, BlueprintReadWrite) bool m_hookfinished; UPROPERTY(EditAnywhere, BlueprintReadWrite) FVector m_hook_location; UFUNCTION(Bluepr...
The SetVisibility and SetWorldLocation functions already have a C ++ implementation. Better to call the entire function from C ++: //.h UFUNCTION(BlueprintCallable) void StopGrapple(); //.cpp void Agrapplecomponent::StopGrapple() { FVector Location(0.f, 0.f, 0.f); m_hooked = false; m_hookfinished = fals...
70,670,143
70,680,246
Initialize member array with constructor argument (with plain old arrays)
Very similar to this: C++ Initialize Member Array with Constructor Argument But I don't use std::array, or rather, really rather not use it if there are other options. I have this class (simplified): template<typename T, int length> // Line 53 class StaticArray { public: T items[length]; StaticArray...
This constructor: template<typename... TNewItems> StaticArray(TNewItems... newItems) : items{newItems...} { static_assert(sizeof...(newItems) == length, "Number of supplied items must match the length of the array."); } Use like this: StaticArray<int, 4> a; // Works (uninitial...
70,670,599
70,671,134
Templated operator=() and overload resolution
Consider the following code snippet: #include <utility> struct test { template <class Other> test& operator=(Other&&); int& i_; }; int main() { int i = 0; test t1{i}, t2{i}; t1 = std::move(t2); // tries to select the implicitly-declared one! } When trying to compile with GCC11.1 (with -std=...
It seems like a bug. It looks for templated method on GCC 11.2 but as you mentioned, it sees deleted method on GCC 11.1.
70,670,604
70,670,815
Avoid code duplication between two functions, but one returns in the middle of the code
Lets say i have two functions inside a class: vector<int> getAllPossibleNumbers() { vector<int> nums; for (int i=0; i < MAX; i++) if (isAPossibleNumber(i)) nums.push_back(i); return nums; } bool hasAtLeastOnePossibleNumber() { for (int i=0; i < MAX; ++i) if (isAPossibleNumbe...
One option would be to move most of the logic into a third function with a callback to the outer functions which gives the numbers. The result of the callback can be used to determine whether to continue the loop: template <typename Callback> void checkNumbers(Callback callback) { for (int i=0; i < MAX; i++) { ...
70,670,766
70,673,487
Copying with memcpy externally?
Is it possible to copy a function to an external application's shared library in memory? If so, how? I'm trying to achieve external hooking by making a trampoline hook externally.
This require very deep understanding of the binary formats used by the operating system. Not all code is relocatable, your code must be compiled with -fPIC for this to work for sure. You will need also to resolve manually all external symbols. In fact, you will have reimplement parts of the ELF loader. It is possible b...
70,671,328
70,671,397
Why segmentation fault in this simple C ++ program?
I am trying to merge two sorted subarrays. I have spent hourse of frustration removing segmentation fault error in vs code but with no success. I am using a temporary array to store the newly ordered array. comparing elements of two subarrays simultaneously and incrementing the index of the subarray whose arr[index] i...
This is an infinite loop: while(i <= end1 ){ temp_arr[start1++] = arr[i]; } So is this one. while(j <= end2){ temp_arr[start1++] = arr[j]; } In both cases, since neither i, j, end1, nor end2 ever change in these loops, start1 will keep increasing way past the array boundary, introducing more undefined behavio...
70,671,329
70,671,385
c++ - conditional assignment of const, without ternary?
suppose I want to assign a const variable based on complex calculations which depend on a conditional. if the situation were simple, I could do: const int N = myBool ? 1 : 2; but it's more like const int N = myBool ? <lengthy calculation> : <other lengthy calculation>; What I'm doing is this, but I'd like something c...
You could wrap each calculation in a lambda, and capture the local variables to reduce the verbosity of their arguments { // ... auto firstFunc = [&]() -> int { ... }; auto secondFunc = [&]() -> int { ... }; const int N = myBool ? firstFunc() : secondFunc(); } In this way only one of the two func...
70,672,136
70,673,480
why "missing double brace warning" for BaseClass Aggregate initialisation in Clang 12 but not Clang 13 or GCC 11?
This code compiles without warning in GCC 11 and Clang 13 (in C++20 mode) struct A { int x, y; }; struct B : A { }; int main () { A a{1,2}; B b{3,4}; // Clang 12 wants B b{{3,4}} return a.x * b.x + a.y * b.y; } but in Clang 12 We get <source>:10:9: warning: suggest braces around initialization o...
C++17 as well as C++20, https://timsong-cpp.github.io/cppwp/n4659/dcl.init.aggr#12 and https://timsong-cpp.github.io/cppwp/n4868/dcl.init.aggr#15, respectively, allows brace elision for the initialization of aggregates: Braces can be elided in an initializer-list as follows. If the initializer-list begins with a left ...
70,672,159
70,672,280
I am working on a project and I am trying to create a folder and a file inside of the folder but it doesn't work
This is my function: void Mail::send_mail(int id, std::string send_to, std::string subject, std::string message) { int receiever_id = find_user(send_to); std::fstream file("/mails/" + send_to + "/" + std::to_string(accounts.at(receiever_id).number_of_mails) + ".txt", std::ios::out); email *mail = new email(...
as @Eugene mentioned in the comments, you cannot create a file inside a directory that doesn't exist. C++ will not create the directory for you first. you can use boost to create the directory first, then proceed with your logic. #include <boost/filesystem.hpp> ​boost::filesystem::create_directory("dirname"); the re...
70,672,879
70,673,697
Linking custom library with libcurl functions
I have a custom static library called "libcurlwrapper", which just wrapps the execution of libcurl functions, and a main app which calls the library's function. Compiling the library works, but when it comes to linking the main app I get these errors: /usr/bin/ld: .//libcurlwrapper.a(curl_wrapper.o): in function `http3...
A static library is compiled into the final executable. External functions used by a static library are just references. The main executable that uses the static library will need to resolve the references to all of the external libraries that the static library refers to. In this case, that means the main executable ...
70,673,381
70,673,429
OpenGL Project - objects not keeping filling color on movement
When I execute the code I get a hot air balloon formed of three elements. My issue is that when I move the objects from the keyboard, the objects loose color, and become more like wire than solid. From what I discovered until now, my trouble comes from this function call: glPolygonMode(GL_FRONT_AND_BACK, GL_LINE) But ...
OpenGL is a state engine. Once a state has been set, it is retained until it is changed again, even beyond frames. Therefore, you need to set the polygon mode GL_FILL before rendering the solid geometry: void CALLBACK display (void) { glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); // render solid geometry // [...
70,673,958
70,679,767
Handling MF_E_TRANSFORM_STREAM_CHANGE from video decoder MFT
I am trying to decode even just a single H264 frame with the H264 Decoder MFT, but I've been having problems with ProcessOutput(). I've reduced the bad HRESULT's as much as I can, but I'm currently stuck on dealing with MF_E_TRANSFORM_STREAM_CHANGE. This occurs after I set the pSample equal to my allocated output_sampl...
You just need to follow this at Handling Stream Changes: The client calls IMFTransform::GetOutputAvailableType. This method returns an updated set of output types. The client calls SetOutputType to set a new output type. The client resumes calling ProcessInput/ProcessOutput. In the question body above you are tryin...
70,674,025
70,677,926
QDoubleValidator and QLineEdit onEditFinished conflict?
I'm hoping to get some insight into a issue I'm facing using QDoubleValidator, I have created a widget to collect some information, and would like to have some fields validated as Double values, I have done so here: orderform::orderform(QWidget *parent) : QDialog(parent), ui(new Ui::orderform) { ui->setupUi(this); this...
Maybe your validator range (0.0 to 5.0) is too narrow. If a newly calculated value falls outside the range, the validator state won't be QValidator::Acceptable anymore, and, as a side effect, the line edit will no longer emit the editingFinished signal. You could try keeping the validator's top() to its default (infini...
70,674,194
70,674,327
Why does my program enters into an infinite loop when my char variable reaches the [del] character (127) value?
Here's my code: #include <iostream> int main() { char x = 32; while (x <= 126) { std::cout << x << "\n"; x += 1; } } Until here, all goes right, but if I change my code to: #include <iostream> int main() { char x = 32; while (x <= 127 /* here the "bad" change */ ) { std::c...
When x reach 127 it's flipped to -128 in the next round [-128 to 127]
70,674,601
70,674,963
How do I declare a member variable within the constructor that doesn't have a predefined type?
I'm trying to declare a member variable of a class with a type that isn't defined during compilation. I read this article where C++17 fixed template constructors by just redacting the type paramater for a template constructor call. (I probably read it wrong because i'm getting errors.) class theClass { template <ty...
The template should be on the class, to have a member use the template parameter: template <typename UDEF> class theClass { UDEF memberVar {}; public: theClass(UDEF var) : memberVar(var) {} }; Now your main can create an object like that: int main() { int number = 3; theClass the(number); // CTAD, C++1...
70,674,723
70,675,458
How to push back a vector onto a vector of vectors using an iterator
I have this code that creates an error: #include <vector> #include <iostream> #include <string> void read_string(std::string &str, std::vector<std::string> &dir, std::vector<std::vector<std::string> > &table, std::vector<std::vector<std::string> > &result) { std::vector<std::vector<std::s...
Oops, yes too many layers (I should have understood the first comment) - This is the desired code - void read_string(std::string &str, std::vector<std::string> &dir, std::vector<std::vector<std::string> > &table, std::vector<std::vector<std::string> > &result) { std::vector<std::vector<std...
70,675,511
70,683,424
IddCX header results in errors for pure C compilation
I am trying to use pure C for a windows driver I am working on. Its a driver using IddCx (um/iddcx/iddcx.h). This header has a 'extern "c"` wrapper to allow for C compilation. The issue is the code within the 'extern "C"' block is not C. I get these two issues. enum declarations like this: enum IDDCX_MONITOR_MODE_ORIGI...
IddCx seems to suppose to be C compliant, but its not. I have reported the issue to microsoft. I have created a temporary custom header file that is compliant. It compiles just fine now.
70,675,513
70,675,581
C++ count() function displays 1's and 0's rather than a total count when reading from a text file
When counting a simple string, this works: string x = "aabbcc"; int n = count (x.begin(), x.end(), 'a'); cout << n; This outputs '2' which is correct. However, when I read in the string from a text file: ifstream myFile; myFile.open(argv[1]); string x; if (myFile.is_open()) { while (myFile) { x = myFile.g...
get() function is extracting a character at a time and passing it to variable X. in every iteration of the while loop, X is of size 1. Variable n contains the counts of 'a' character in the One character X has in it. so, your output is instead number of a's in every single character of the file. For the case when the c...
70,675,605
70,675,680
Is there a better way to see which function caused a exception other than using catch
I'm having problems with locating the address from which a error occurred, my whole code is running inside of a "try" statement and sadly whenever something is wrong I need to find the error using the old try and fail method by deleting parts of my code. Is there a better way to do it? My current code: try { do ...
A simple solution to find out where an exception comes from is to use a unique message within each function. Catch the exception object and print the message. Or perhaps use even a different type of exception which will allow you to efficiently handle each case differently if that's what you want to do. As for getting...
70,675,775
70,675,873
How to calculate if a point is within a circle
I am given a constructor: Circle::Circle(const Point& c, float r) { x_ = c.getX(); y_ = c.getY(); r_ = r; } All values have been initialised as shown. In the parameter I have Point& - This just allows me to get the x and y coords using a function from a different class. Also, I have "r" which will take in ...
To check whether point lies inside circle, you need to implement this formula (strict < if you don't need points at circumerence): (px-cx)*(px-cx) + (py-cy)*(py-cy) <= r*r Squared distance from point to center should be less than squared radius (to avoid sqrt calculation) For your example (3.9-1)^2+(2-2)^2 = 8.41 < 3...
70,676,083
70,679,095
Returning the right number of islands using Union Find
I am solving a question on LeetCode.com called Number of Islands: Given an m x n 2D binary grid grid which represents a map of '1's (land) and '0's (water), return the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edge...
Add some debug print shows some issues in union: Demo. Changing to: void unionf(int one, int two) { int p1=find(one); int p2=find(two); if (p1 == p2) return; if (sz[p1] < sz[p2]) { parent[p1] = p2; sz[p2] += sz[p1]; } else { parent[p2] = p1; sz[p1] += sz[p2]; ...
70,676,092
70,679,213
CodeLite IDE is not reading file
So I have a Test folder inside my workspace in CodeLite and inside Test folder I have: main.cpp test.txt The problem is whenever I try to read from test.txt, the compiler deletes the file content and writes "Debug/main.cpp.o" inside my test.txt file. For example, if my txt file contains the following text: Abcd ef An...
Codelite generates $(project).txt ($(project) is Test in your case) with all objects filename for compilation (as response file (to bypass limit of command line length when there are too many files)). Either place project in another directory or rename the file or project to avoid the conflict with that file.
70,676,299
70,676,516
"Unresolved external symbol" for global variables
I created a global file (Globals.h) to hold my global renderer (gRenderer) and my global window (gWindow). I declared them as extern as they'll be defined inside initWindow() & initRenderer() functions under InitChess.cpp. Some reason the linker is complaining that I have "unresolved external symbols", even though I de...
There is a difference between a declaration and a definition. Usually writing SDL_Window* gWindow; is a declaration and a definition of the variable gWindow. Every (non-inline) variable that your program uses can have multiple declarations, but must have exactly one definition. Putting extern before SDL_Window* gWindo...
70,676,313
70,680,207
Why does this spinlock require memory_order_acquire_release instead of just acquire?
// spinlockAcquireRelease.cpp #include <atomic> #include <thread> class Spinlock{ std::atomic_flag flag; public: Spinlock(): flag(ATOMIC_FLAG_INIT) {} void lock(){ while(flag.test_and_set(std::memory_order_acquire) ); // line 12 } void unlock(){ flag.clear(std::memory_order_release); } }; Spinl...
std::memory_order_acq_rel is not required. Mutex synchronization is between 2 threads.. one releasing the data and another acquiring it. As such, it is irrelevant for other threads to perform a release or acquire operation. Perhaps it is more intuitive (and efficient) if the acquire is handled by a standalone fence: vo...
70,676,414
70,679,691
how to make a collision of an actor on a character in C++ UE4?
I’m looking to make items that contain powers on unreal engine in c++ like : When the player steps on it, he wins the Mushroom effect: It has a scale of 1.25x. So I create my Actor Item which contains the beginoverlap and the power function : Item.h #pragma once #include "CoreMinimal.h" #include "Components/CapsuleC...
I didnt quite understand. Do you want the player to step on the object and increase in size and then, when he leaves the object, return it to its original size (1) or keep the size (2)? //.h UFUNCTION() void Power(); UFUNCTION() void ResetPower(); bool bIsPower = false; //.cpp void AItem::ResetP...
70,676,905
70,677,168
`int (*q)[m][n]=( int(*)[m][n] )p;` is this typecasting possible where p is normal integer pointer `int *p` which pointing to base address of matrix
Code #include <iostream> void display(int, int, void* ); int main() { int A[][2]= { 0, 2, 4, 2, 2, 2}; int m=3, n=2; display(m, n, &A[0][0]); } void display(int m, int n, void *p) { int (*q)[m][n]=( int(*)[m][n] )p; // This causing error for(int i=0; i<=m-1; i+...
You don't have to use vectors for statically sized data you can still use "C" style arrays. AND you can do it in a typesafe (and memory access safe way) as shown here : #include <iostream> /* This is an insecure way of doing things anyway since it depends on - typeconversion from void* (you could put anything into th...
70,677,039
70,677,813
While running my linked list code the compiler does not give any outputs after giving a print function too
I have given insert and a print function to insert data in a linked list and then print it. But somehow it does not give any output and keeps running for a infinite time. What is wrong? Here is the code I have written. This is a simple program to create a linked list using loops and functions. #include<iostream> using ...
There were few bugs in your code and also typos. Please read the comments marked with // CHANGE HERE for the description of the changes I did: #include <iostream> using namespace std; struct node{ int data; struct node* next; }; struct node* head; void insert(int data){ struct node* temphead = head; if...