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,334,227
73,364,666
Why is gcc not catching an exception from a multi target function?
I'm using the target attribute to generate different function implementations depending on the CPU architecture. If one of the functions throws an exception it doesn't get caught if I compile with gcc, but with clang it works as expected. If there is only a single implementation of the function it does work for gcc as ...
I reported this and a GCC developer confirmed it as a bug: link For now a workaround seems to wrap the function and use the gnu::noipa attribute to disable interprocedural optimizations: __attribute__((target("default"))) void f() { throw 1; } __attribute__((target("sse4.2"))) void f() { throw 2; } [[gnu::noip...
73,334,632
73,340,871
Are incremental builds possible with copied files not built on the machine?
I'm having trouble setting up incremental builds in Azure DevOps. There are too many variables with workspace cleaning to ensure that I don't have to do a full build every time. I had a thought that I could just always copy the built files to a location outside of the agents' purview, and then copy those files into my ...
You probably can 'fool' the incremental logic but you would be working against the tooling. For an actual incremental build you need to build in the same place. In the context of Azure DevOps, that means building the same job of the same pipeline on the same agent. You can't let the build move around between agents or ...
73,335,101
73,335,323
c++ task won't execute after while loop
C++ newbie here. I'm not sure how to describe this but the task outside of the while-loop won't execute immediately. I need to enter the input value again to get it done. Here is my code: #include <iostream> using namespace std; int main() { int fourDigitInt, firstDigit, secondDigit, thirdDigit, fourthDigit, i = ...
The main issue here is in the while loop condition. It should just check for the value of the fourDigitInt variable as that is what is important. Looking closer, you will also be able to notice the fact that the if case inside of the loop would check for the second iteration instead of the third. I fixed that as well b...
73,335,380
73,335,780
Frequently insert and delete elements using std::vector
I have a game which could have a million "boxes". For convenience, I use std::vector<shared_ptr<Boxes>> to save them. But today, I want to break some "box" if the box is subjected to a certain impact, so I have to split the box into "two small boxes". Here is the question - in the game, there are so many "boxes" that w...
Starting from an empty data structure: std::vector<std::shared_ptr<Box>> boxes; We can reserve capacity for 2 million boxes. This is probably too much, but allows for each box to be split once: boxes.reserve(2_000_000); Now, at the start of the game you can use push_back to fill up this vector. At some later point, y...
73,336,245
73,336,277
const char* allows to modify the string?
I understand that using const char* is a modifiable pointer to a constant character. As such, I can only modify the pointer, but not the character. Because of this, I do not understand why I am allowed to do this: const char* str{"Hello World"}; str = "I change the pointer and in turns it changes the string, but not r...
No string was replaced, you just reassigned str a new string which is stored on stack-memory. Try this snippet, that the address was changed #include <stdio.h> int main(void) { const char *ptr = "Hello"; printf("Before: %p\n", ptr); ptr = "World"; printf("After: %p\n", ptr); } Output [RESULT MAY VARY...
73,336,458
73,336,613
Can I compute values that require a special function during compilation of C++?
I appreciate I am being somewhat vague about what is exactly my issue, but I think that the fundamental question is clear. Please bear with me for a moment. In brief, I have a static constexpr array of points which are used to find certain bounds I need to use. These bounds depend only on the array, so they can be prec...
constexpt std::vector does not work here, but you can use std::array. std::exp is not constexpr so you need to find constexpr alternatives it would work in gcc as an extension. static constexpr double CHECK_POINTS[7] = { -1.5, -1.0, -0.5, 0.0, -0.5, 1.0, 1.5 }; static constexpr auto vec = [](){ std::array bo...
73,336,690
73,336,691
Supertype of std::plus and std::minus / how can I use std::plus and std::minus in a single object?
I was trying to simplify a piece of code by removing redundant code that only differed in += and -=. My idea was to use std::plus and std::minus instead and thus combine the two methods into one. Minimal code is: #include <functional> int main() { // true is actually some condition std::binary_function<long, lo...
The inheritance from std::binary_function<T, T, T> was removed in C++11. Also, std::binary_function changed in C++11 and changes in C++17 again. You can use function instead: std::function<long(long, long)> direction = true ? static_cast<std::function<long(long, long)>>(std::plus<long>()) : std::minus<long>(); ...
73,337,020
73,337,829
Behaviour of simple multithread program on C++
I'm training on C++ and threads. I found the following code from this page and compiled it on my Ubuntu 20.04 machine: // C program to show thread functions #include <pthread.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> void* func(void* arg) { // detach the current thread // from the calling ...
A spotted in the comments, the source of the main issue of your code is that you call pthread_detach. The later pthread_join will just ignore the thread you detach. At this point all thread "live their own life" which means the the only remaining synchronization mechanism is at the "exit" (when main returns). On exit, ...
73,338,291
73,338,420
How to use template template as template argument properly?
I have this code with error: template <typename T1> struct A { template <typename T2> struct B { using type = char /* actually some class depending on T1 and T2 */; }; template <typename T2> using type = B<T2>; }; template <template <typename> class TT> struct C { template <typename T> ...
You need template, but in a different place: using type = typename C<A<T>::template type>::type; // ^~~~~~~~ IIRC, it becomes optional and deprecated in C++23 (that is, template followed by an identifier without <...> after it).
73,338,485
73,359,193
Sometimes Qt's paintGL does not draw an OpenGL edge of Bullet's Physics colliders
It works 50 by 50%: I use a timer for redrawing: void Widget::animationLoop() { m_deltaTime = m_elapsedTimer.elapsed() / 1000.f; m_elapsedTimer.restart(); m_pWorld->stepSimulation(m_deltaTime, 8); update(); } I call collider's drawing (m_pWorld->debugDrawWorld();) like this: void Widget::paintGL() { ...
I forgot to get the uMvpMatrix location in the ColliderEdge class: ColliderEdge::ColliderEdge(QOpenGLShaderProgram *program, const VertexBuffersData &vertexBuffers) : m_pProgram(program) { m_vertPosBuffer = vertexBuffers.vertPosBuffer; m_amountOfVertices = vertexBuffers.amountOfVe...
73,339,042
73,340,039
Is there a way to embed a web browser inside of an ImGui Window?
Question: Hello, I am looking for a way to embed a web browser inside of an ImGui Window, kind of like a button or text control. Is there a library, hacky workaround or something of that sort, that I could use without switching to a different UI library (because some features in the project still have regular imgui). T...
Since you also are willing to accept a "hacky" approach to this, you can in programmer terms "borrow" some code from this repository which is a full CEF (Chromium Embedded Framework) implementation inside of ImGui. Found this while browsing the issues of Ocornut's ImGui. Comment and repo on GitHub by hendradarwin It ...
73,339,565
73,339,663
build and pass list of types to variadic templates
I'm very new to meta-programming and I'm experimenting with some examples. I've designed a variadic template class as follows: template <typename TA, typename... TB> class A [...] This could be instantiated simply by passing different types like A<Class1, Class2, Class3> * a = &(A<Class1, Class2, Class3>::instance());...
Big fat warning: don't do this. The reason I'm saying, it'll change during the code. As you gradually add types, you'll end up defaultTypeList having multiple meanings in different places of the code. That said... Can it be done? Of course, #define DEFAULT_TYPE_LIST typelist<>() // ... #ifdef MACRO1 static constexpr a...
73,339,664
73,339,874
target_include_directories not including INTERFACE library
# Adding a header-only library set(INCLUDE_LOCATION "${PROJECT_SOURCE_DIR}/../include") add_library(myLib INTERFACE) target_include_directories(myLib INTERFACE "${INCLUDE_LOCATION}") # Printing the include paths for the header only target get_target_property(dirs myLib INCLUDE_DIRECTORIES) foreach(dir ${dirs}) mes...
Interface libraries don't have non-INTERFACE properties. INCLUDE_DIRECTORIES is simply invalid here. You are looking for INTERFACE_INCLUDE_DIRECTORIES. cmake_minimum_required(VERSION 3.24) project(test) set(INCLUDE_LOCATION "${PROJECT_SOURCE_DIR}/../include") add_library(myLib INTERFACE) target_include_directories(myL...
73,339,793
73,339,872
How to understand this std::bind usage
I am trying to understand this usage of std::bind(). For this example: std::bind(&TrtNodeValidator::IsTensorRTCandidate, &validator, std::placeholders::_1) They are trying to bind the function TrtNodeValidator::IsTensorRTCandidate(). However, according to the definition of this API: Status TrtNodeValidator::IsTensorRT...
TrtNodeValidator::IsTensorRTCandidate() is a non-static member function. Aside from its explicit parameters, it requires a TrtNodeValidator* to become its implicit this parameter. This usage: std::bind(&TrtNodeValidator::IsTensorRTCandidate, &validator, std::placeholders::_1) will produce a callable object ...
73,340,077
73,340,918
Catch2 CLion error, "No tests were found"
I have a folder structure like and I am trying to get Catch2 setup, my CMake files look like: the topmost CMake: cmake_minimum_required(VERSION 3.21) project(throwaway) set(CMAKE_CXX_STANDARD 14) add_subdirectory(src) add_subdirectory(tests) add_executable(foo_main main.cpp) target_link_libraries(foo_main PUBLIC fo...
Figured out it from the links at How do you add separate test files with Catch2 and CMake? in my tests/foo CMake I changed it to add_library(foo_test_lib OBJECT FooTests.cpp) target_link_libraries(foo_test_lib PUBLIC foo_lib)
73,340,220
73,340,438
inline function in an array of functions, good idea for performance?
The question is in the title but it's not necessarily clear so here's a code example of what I wanted to do: #include <iostream> typedef void (*functions)(void); inline void func_A() { std::cout << "I am A !" << std::endl; } inline void func_B() { std::cout << "I am B !" << std::endl; } int main() { fun...
You can easily look at the output of the compilers to see how they handle your code. Here my results for current compilers with O2 optimization flags, see https://godbolt.org/z/ecjjz88hs. Current MSVC seems to not optimize the calls at all. It doesn't even unroll the loop and therefore also doesn't determine which func...
73,340,368
73,340,376
how to force shutdown computer using cpp program
i have been working on a small project. i am making a timer for my little brother's PC so that he will not be able to use computer more than set time by me in a day. The problem I am facing in my code is I have tried bunch of system commands to shut down computer automatically but when it runs the command it asks to we...
You need to add the /f flag to force a shutdown.
73,340,416
73,340,452
When does a struct require a default constructor?
I wrote a struct with custom constructor designed to be a data member of a class: struct HP { int max_hp; int hp; // HP(){}; it is required for the next class constructor function. Why? HP(int max_hp) { this->max_hp=max_hp; this->hp=max_hp; } }; class Character { protected: HP h...
All class members are initialized before entering the body of the constructor. Character::Character(int hp) { // already too late to initialize Character::hp this->hp = HP(hp); // this is an assignment } Without a HP default constructor, Character(int hp); cannot initialize its hp member unless it can provide argu...
73,340,907
73,341,083
If C and C++'s double (and float) is IEEE 754-1985, then are the integer representations and Infinity, -0, NaN, etc, all left unused?
It appears that JavaScript's number type is exactly the same as C and C++'s double type, and both are IEEE 754-1985. JavaScript can use IEEE 754 as integers but when the number becomes big or gets an arithmetic calculation such as divided by 10 or by 3, it seemed like it can switch into floating point mode. Now C and C...
If that's the case, isn't it true that the IEEE 754's representations of [integers and some special values] were all unused, as C and C++ didn't have the capability of referencing them? This notion appears as if it might stem from the fact that JavaScript uses the IEEE-754 binary64 format for all numbers and performs...
73,340,921
73,340,979
How to visualize layout of C++ struct/class
What is the best way to visualize the memory layout of a C++ class/struct, compiled by GCC? I added the GCC switch -fdump-lang-class to my C++ compile options but it didn't output anything to stdout, nor did I notice any files .class files created. I just want to see the size/offsets of class/data members.
You can use pahole. It is a swiss army tool for this kind of things. https://manpages.ubuntu.com/manpages/impish/man1/pahole.1.html For example, say you have this test.cpp file struct A { int i; char c; double x; }; void doit( A& a ) { a.i = 1; a.c = 0; a.x = 1.0; } Let...
73,340,981
73,341,008
Smart pointers still refers to raw pointer even though reset is applied
Please find the code attached which I took from https://www.geeksforgeeks.org/auto_ptr-unique_ptr-shared_ptr-weak_ptr-2/ for testing the smart pointers. // C++ program to demonstrate shared_ptr #include <iostream> #include <memory> class A { public: void show() { std::cout << "A::show()" << std::endl; ...
It works because you are not using any member from the object otherwise it would segfault. But a sanitizer catches this very easily: $ g++ -ggdb -O0 -fsanitize=undefined,address shared.cpp -o shared $ ./shared 0x602000000010 A::show() A::show() 0x602000000010 0x602000000010 2 2 0 1 0x602000000010 shared.cpp:33:13: runt...
73,341,125
73,341,165
Disable GCC narrowing conversion errors
I have code from over 20 years in C/C++ and one technique used to handle variable data sizes was to let automatic type conversion handle it. For example: #define MY_STATUS_UNDEFINED (-1) Then if it was compared/used against a int64_t it was auto expanded to -1LL, for uint64_t to 0xFFFFFFFFFFFFFFFF, for uint32_t to 0xFF...
Using the following brief example: #include <cstdint> #include <iostream> #define MY_STATUS_UNDEFINED (-1) void bar() { std::cout << "It works\n"; } void foo(uint32_t n) { switch (n) { case MY_STATUS_UNDEFINED: bar(); break; } } int main() { foo(0xFFFFFFFF); return 0; } You ...
73,341,181
73,341,214
C++ Vector of Objects, are they all named temp?
New to C++ OOP, I recently learned about classes and objects. I created a straightforward class and menu-driven program that adds a temp object to a vector of movies. I have a quick question that I can't quite understand. Am I just pushing multiple "temp" objects into the vector? In my head i'm visualizing this as vect...
In your case, when you are calling push_back it will copy your "temp" object, which is a local object on the stack. It will be copied into a new object which is stored on the heap, held by the vector object. The vector will store these as an array internally (the default vector with the default allocator etc). It's als...
73,341,560
73,341,770
For C/C++, when people say code is insecure, does it mean the application will crash, or it can be abused to launch cyber attack?
I have seen in many instances when people say codes are "insecure". Accessing an array beyond bound is "insecure". Malloc without free is insecure. Dangling pointer is "insecure". No bound checking user input is "insecure". In the above example, I understand in the fourth instances, under specific context, such as if...
Invocation of undefined behavior is always insecure. The first item (array access our of bounds) is automatically in that category. The fourth is just an example of the first, conditional on user interaction (those pesky users). I.e. the potential to overreach an input buffer has the potential to invoke undefined behav...
73,342,306
73,342,375
Can the boost::asio timer object be deleted before the corresponding callback is called?
Should the timer object exist until the task is completed? I mean the following: boost::asio::io_service io; { boost::asio::steady_timer timer(io, std::chrono::seconds(5)); timer.async_wait(someCallback); } // the timer object is deleted here io.run(); Is this allowed and does it lead to undefined behavior?
The destructor simply cancels any pending waits so your callback will be called with the boost::asio::error::operation_aborted error code.
73,342,473
73,342,598
Is there a shorthand method to writing move constructors?
I have a class with one strong pointer and a lot of object members. Writing copy and move constructors for an object like this involves a lot of tedious copy/pasting, however... Is there any way to shorten this, without giving up my beautiful naked pointer? Like if I could perform the default generated move operation...
Use a unique_ptr with a custom deleter. #include <memory> #include <vector> #include <cstdint> #define STRONG /* ??? */ void disengageDevice(char STRONG*); #define B737M_mpDevice 1 char STRONG *getDevice(int, ...); void engageDevice(char STRONG *); class Example { public: Example() : m_multiplexDevice( ...
73,342,779
73,361,229
How alternative deductions can yield more than one possible "deduced A"?
Per [temp.deduct.call]/5 These alternatives ([temp.deduct.call]/4) are considered only if type deduction would otherwise fail. If they yield more than one possible deduced A, the type deduction fails. [ Note: If a template-parameter is not used in any of the function parameters of a function template, or is used only ...
template<typename> struct B {}; struct D : B<int>, B<double> {}; template<typename T> void f(B<T>); int main() { f(D{}); } [temp.deduct.call]/(4.3): If P is a class and P has the form simple-template-id, then the transformed A can be a derived class D of the deduced A. applies here, and 2 deduced As are possi...
73,342,924
73,343,003
reference type as type traits / concept argument
In the specification-mandated implementation of the concept std::uniform_random_bit_generator, it is required that invoking operator() on an instance of type G satisfying this concept should return the same type as G::min() and G::max(). Why is std::same_as<std::invoke_result_t<G&>> used instead of std::same_as<std::in...
std::invocable<G&> checks whether an lvalue of type G can be invoked (without arguments). std::invocable<G> checks whether a rvalue of type G can be invoked (without arguments). std::invoke_result_t is equivalently the corresponding return type. In other words this guarantees that the generator can be declared as a var...
73,342,965
73,343,391
Concept and templates no longer run with g++-11
The following code : #include <cstdio> #include <string> #include <concepts> template<typename T, typename KEY, typename JSON_VALUE, typename...KEYS> concept json_concept = requires(T t, int index, std::string& json_body, KEY key, JSON_VALUE value, KEYS... keys) { { t.template get_value<T>(keys...) } -> std::same...
You are not using concepts with template parameters correctly. Clang is totally wrong in accepting your code. Its support for concepts doesn't seem to be mature enough. If you have: template <typename A, typename B, typename C> concept foo = ... then the correct usage of foo is with two template type arguments: templa...
73,343,345
73,347,449
What does "double + 1e-6" mean?
The result of this cpp is 72.740, but the answer should be like 72.741 mx = 72.74050000; printf("%.3lf \n", mx); So I found the solution on website, and it told me to add "+1e-7" and it works mx = 72.74050000; printf("%.3lf \n", mx + 1e-7); but I dont know the reason in this method, can anyone explain how it works? A...
To start, your question contains an incorrect assumption. You put 72.7405 (let's assume it's precise) on input and expect 72.741 on output. So, you assume that rounding in printf will select higher candidate of possible twos. Why? Well, one could consider this is your task, according to some rules (e.g. fiscal norms fo...
73,343,501
73,343,912
Replacing even digits in string with given string
I know how to replace all occurrences of a character with another character in string (How to replace all occurrences of a character in string?) But what if I want to replace all even numbers in string with given string? I am confused between replace, replace_if and member replace/find functions of basic_string class, ...
You can use std::string::replace() to replace a character with a string. A working example is below: #include <string> #include <algorithm> #include <iostream> #include <string_view> void replace_even_with_string(std::string &inout) { auto is_even = [](char ch) { return std::isdigit(static_cast<unsigne...
73,343,631
73,343,983
std::map::reverse_iterator doesn't work with C++20 when used with incomplete type
I noticed that the use of std::map::reverse_iterator in the below example doesn't work with C++20 but works with C++17 in all compilers. Demo Demo MSVC #include <map> class C; //incomplete type class Something { //THIS WORKS IN C++17 as well as C++20 in all compilers std::map<int, C>::iterator obj1; ...
It works by chance pre-C++20, by standard it's UB to use incomplete types in std containers (with the exception of vector, list and forward_list since C++17). See here. Thus, it may work and may stop working at any time, but basically anything can happen and it should not be relied on. If being able to store an incompl...
73,343,857
73,347,357
Can't write to the video memory from a function with c++ (OS dev)
I want to make a simple function that prints a char to the screen: unsigned char *_videoMEM = (unsigned char*)0xb8000; int c_pos = 0; void printf(char c){ //var 1 _videoMEM[c_pos++] = (char)c; _videoMEM[c_pos++] = 0x0f; //var 2 *((char*)0xb8000 + c_pos++) = c; *((char*)0xb8000 + c_pos++) = 0x0f...
soooo i found the problem, i accidentally misplaced 0x1010010 (int the GDT descriptor) and that needed to be binary BUT, i found another problem, somehow, unsigned char *_videoMEM = (unsigned char*)0xb8000; dose not init the pointer so the solve whoud be like this: char *BASE = 0; int pos = 0; void print(int color, co...
73,343,887
73,344,715
Reading byte from Output Register of I/O Expander via I2C
The below Arduino code snippet shows a function that should return a byte read from the Output Register of an I/O Expander TCA9535 via I2C. I oriented my code at the TCA9535 Datasheet Figure 7-8, seen here: https://i.stack.imgur.com/GgNAQ.png. However, calling readOutputRegister() always returns 255. uint8_t readOutput...
First, from Wire.endTransmission() reference page. This function ends a transmission to a peripheral device that was begun by beginTransmission() and transmits the bytes that were queued by write(). For Wire library, many people think Wire.write() would send the data, it is actually not, it only put the data on a que...
73,344,127
73,373,790
Division using right shift operator gives TLE while normal division works fine
I'm trying to submit this leetcode problem Pow(x,n) using iterative approach. double poww(double x, int n) { if (n == 0) return 1; double ans = 1; double temp = x; while (n) { if (n & 1) { ans *= temp; } temp *= temp; n = (n >> 1); } ...
The problem is the given input range for "n". Let us look at the constraints again: The problem is the smallest number for n, which is -2^31 and that is equal to -2147483648. But the valid range for an integer is -2^31 ... 2^31-1 which is -2147483648 ... 2147483647. Then you try to use the abs function on -2147483648....
73,344,188
73,344,630
Android oboe glitch/noise/distortion
I'm trying to use oboe in my audio/video communication app, and I'm trying the onAudioReady round-trip callback as in the oboe guide: https://github.com/google/oboe/blob/main/docs/FullGuide.md Now I'm frustrating: If the read directly write into the *audioData, the sound quality is perfect, i.e.: auto result = record...
I've figured it out because the channel is stereo, samples per frames are 2, i.e.: auto result = recordingStream->read(buffer, numFrames, 0); std::copy(buffer, buffer + numFrames * 2, static_cast<int16_t *>(audioData));
73,345,030
73,345,267
Copy-elision in direct initialization from braced-init-list
In the following program the object A a is directly initialized from braced-init-list {A{}}: #include <iostream> struct A { int v = 0; A() {} A(const A &) : v(1) {} }; int main() { A a({A{}}); std::cout << a.v; } MSVC and GCC print 0 here meaning that copy-elision takes place. And Clang prints 1 ...
Which compiler is right here? I think that clang is right in using the copy constructor and printing 1 for the reason(s) explained below. First note that A a({A{}}); is direct-initialization as can be seen from dcl.init#16.1: The initialization that occurs: 16.1) for an initializer that is a parenthesized expressi...
73,345,258
73,353,134
Why is identifier "MutexType" is undefined?
Attempting to use the boost library to create a system wide mutex from the docs #include <boost/interprocess/sync/interprocess_mutex.hpp> #include <boost/interprocess/sync/scoped_lock.hpp> #include <boost/interprocess/sync/named_mutex.hpp> using namespace boost::interprocess; MutexType mtx; int main() { return...
The linked documentation specifically means "any mutex type": //Let's create any mutex type: MutexType mutex; It follows it up with a concrete, more elaborate Anonymous mutex example and Named mutex example. Which types are eligible is documented at scoped_lock: scoped_lock is meant to carry out the tasks for locking...
73,345,683
73,345,811
What are the optimal data structures for implementing a hidden layer neural network with backpropagation in C++?
Apologies if this seems like a duplicate post, but I am wondering what the optimal data structures for implementing and storing a simple hidden layer neural network with weights and biases and backpropagation in C++ are. Off the top of my head I was thinking about the following: Linked list Pointer array These two se...
One option I see is doing it like this: Have one linear array for the nodes and one for all the edges. A sketch: struct Node { std::size_t edgeBegin; std::size_t edgeEnd; }; struct Edge { std::size_t to; float weight; }; struct Layer { std::size_t layerBegin; std::size_t layerEnd; }; struct Network { std:...
73,345,926
73,347,079
How to create a HICON from base64?
I am converting a picture from a base64 string into an HICON that could work when registering a new class: WNDCLASSEX wc{}; wc.hIcon = < here >; I got the base64_decode() function here: base64.cpp #include <windows.h> // GDI includes. #include <objidl.h> #include <gdiplus.h> using namespace Gdiplus; #pragma comment (l...
cannot convert argument 1 from 'Gdiplus::Image' to 'Gdiplus::Image *' DrawImage() expects a pointer to an Image object, but you are passing it the actual object instead. Change this statement: gg->DrawImage(image, 0, 0, wd, hgt); To this instead: gg->DrawImage(&image, 0, 0, wd, hgt); // <-- note the added '&' ...
73,346,040
73,346,651
Is there any way to know how much space a function takes (or possibly can take) in CPU cache?
I'm just starting to learn about CPU cache in depth and I want to learn how to estimate a functions instruction size in CPU cache for curiosity reasons. So far I learned it's not very easy to monitor L1 cache by surfing in SO and Google. But surprisingly I couldn't find any posts explaining my question. If it's not pos...
Can you measure it? Yes. Take a look at the output of a disassembler or measure the size increase of the library. Should you worry about it? Absolutely not. The executable code is usually tiny. If you're going through it once, even if we're talking GBs it's going to be fast. The usual way to make things slow is loo...
73,346,429
73,347,923
How to get a pointer to the bytes of a uint32_t
I'm trying to create a complete uint32_t using vector of uint8_t bytes. It should be filled iteratively. It can happen in any of the following ways: 1 byte and 3 bytes. 2 bytes and 2 bytes. 4 bytes. 3 bytes and 1 byte. uint32_t L = 0; uint32_t* LPtr = &L; std::vector<uint8_t> data1 = {0x1f, 0x23}; mem...
The problem is you're using a pointer to uint32_t so incrementing it won't make it iterate by 1 byte, only by 4 bytes. Here is a version which populates all bytes of L, but it's still messing with endianness: uint32_t gimmeInteger(std::vector<uint8_t> data1, std::vector<uint8_t> data2) { assert((data1.size() == 2)); ...
73,346,507
73,346,547
CMake not finding include file I specified
I am trying to use CMake to debug a JUCE distortion project I'm working on but I can't get the CMakeLists.txt file find the header file JuceHeader.h so it can build and debug the project. So here's what the file structure looks like: distort (CMakeLists located here) | |_______Source | | | |________PluginEd...
I suppose home/wolf/vst/distort/JuceLibraryCode/ should be an absolute path, but relative one was given. But the absolute path is not a solution. target_include_directories(Distort PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/JuceLibraryCode) Or just like bellow target_include_directories(Distort PRIVATE JuceLibraryCode)
73,346,834
73,347,405
Running C++ code asynchronously in a C# program
I wrote some backend code in C++ and I wrote a frontend for it in C#. What I want it to do is run the backend code in the background so I can do other things like update a progress bar, but when I click the "Start" button, the program hangs until it's finished running the backend code. C# code: [DllImport("backend....
You can wrap the call to executeBackend in a Task to prevent the UI from locking up. var status = await Task.Run(() => executeBacked()); I also think you're confused about what the async keyword actually does. I think it might be prudent for you to read up on how Asynchronous Programming works in dotnet.
73,347,657
73,348,005
A shared pointer to a section of memory belonging to another shared pointer
I know shared pointers are implied to share the same memory. But what if my shared pointer points to an element which is not the first in the memory of another shared pointer? Consider a raw pointer example: int* array = new int[10]; int* segment = &array[5]; Can I make the same thing with array and segment being shar...
std::shared_ptr has an aliasing constructor for exactly this kind of situation: template< class Y > shared_ptr( const shared_ptr<Y>& r, element_type* ptr ) noexcept; The aliasing constructor: constructs a shared_ptr which shares ownership information with the initial value of r, but holds an unrelated and unmanaged p...
73,347,714
73,347,954
Errors when passing pointer to structs c++
I am a beginner in C++, so I'm sure the error is from my misunderstanding of pointers. I was making a Poker game, where card is a struct with the suit and the value, and each player's hand is filled with cards, and the middle is filled with cards. I passed references of the arrays to a function by reference, but I thin...
In your function's parameters, you are using the wrong syntax to accept the arrays by pointer. And, you are declaring the wrong element type for the arrays (you claim card* pointers, but the arrays actual hold card objects instead). And, your function is treating the mid_cards parameter like it is a pointer to a 2-di...
73,347,788
73,347,837
Error when calling QFlags::testFlag() with bitwise OR of flags
I am trying to test if one or both of 2 flags are set, using a single testFlag command as follows: myFlags.testFlag(QIODevice::ReadWrite | QIODevice::Append) which generates this compiler error: error: no viable conversion from 'QFlags\<QIODevice::OpenMode::enum_type\>' (aka 'QFlags\<QIODevice::OpenModeFlag\>') to 'QI...
The flags should be tested by one. bool QFlags::testFlag(Enum flag) const is declared to accept a single flag, for multiple flags it would accept int. It is also obvious from the name "testFlag" not "testFlags". if (myFlags.testFlag(QIODevice::ReadWrite ) && myFlags.testFlag(QIODevice::Append)) cout << "true"; else...
73,348,154
73,348,180
Value initialization of template object using new
I have a class with a pointer to T template <typename T> class ScopedPtr { T* ptr_; public: ScopedPtr(); ~ScopedPtr(); //Copy and move ctors are removed to be short } template <typename T> ScopedPtr<T>::ScopedPtr() : ptr_(new T{}) {} And I want to use it as follows: struct Numeric_t { int integer_; ...
The usual perfect forwarding comes to mind: template <typename T> template <typename... Args> ScopedPtr<T>::ScopedPtr(Args&&... args) : ptr_(new T{std::forward<Args>(args)...}) {}
73,348,522
73,348,567
Which operation is not trivial here?
Compilers agree, that the below X and Y are default-constructible, but not trivially (demo). #include <type_traits> struct X { int x {}; }; struct Y { int y = 0; }; static_assert(std::is_default_constructible_v<X>); static_assert(std::is_default_constructible_v<Y>); static_assert(!std::is_trivially_default_constructi...
https://en.cppreference.com/w/cpp/language/default_constructor#Trivial_default_constructor says: The default constructor for class T is trivial (i.e. performs no action) if all of the following is true: ... T has no non-static members with default initializers. (since C++11) ...
73,348,816
73,349,078
How to properly satisfy all linker dependencies in following pybind11 project?
I am porting a large library to pybind11 for python interface. However I have stuck where I seemingly am either getting multiple declaration error at linker stage, or during python import I get symbol not found error. The simplified project structure is as given below CMake file cmake_minimum_required(VERSION 3.5) # s...
The problem is that Stencil.h gets included by both py_modules.cpp and SubConfiguration.cpp. The include guards will only protect against double includes from a single compilation unit (cpp file). Remove the implementation of the Stencil constructor from Stencil.h and move it into a new file Stencil.cpp as #include "St...
73,349,477
73,349,689
Segmentation fault occurs when variable set to indexed parameter
I have a poker game where an array of the players' hands and an array of the cards in the middle are passed as arguments to a function. In the function get_winner, I can loop over and print the cards in the arrays (2nd and 3rd for loops), but if I set a variable to an element of an array and print it, I get a segmentat...
Your function's 1st loop is accessing the commun_cards array incorrectly. Its 3rd loop is accessing the array correctly. Why would you expect the 1st loop to need to access the elements any differently than the 3rd loop just because it wants to save each element to a variable? Since you are passing in each array by poi...
73,349,982
73,350,008
Why do I need std::endl to reproduce input lines I got with getline()?
I am a newbie learning C++ to read or write from a file. I searched how to read all contents from a file and got the answer I can use a while loop. string fileName = "data.txt"; string line ; ifstream myFile ; myFile.open(fileName); while(getline(myFile,line)){ cout << line << endl; } data.txt has three lines of c...
endl means "end line" and it does two things: Move the output cursor to the next line. Flush the output, in case you're writing to a file this means the file will be updated right away. By removing endl you are writing all the input lines onto a single output line, because you never told cout to go to the next line.
73,350,449
73,350,700
How to get error.h in visual studio or equivalent?
I have large C++ project that I inherited and am trying to transfer it from Linux to Visual Studio on Windows. Managed to link required libraries, but one build error just baffles me. In Linux, someone was including a header <error.h> everywhere, and I can't even find a documentation page to see what it is. First I tho...
error.h is a header from the GNU C Library. It is not specific to Linux, it is specific to glibc. It is documented right here (search on the page for error.h). The functions declared in error.h should not be used in portable code, so getting rid of code that uses them is not a bad idea. Alternatively, it is not difficu...
73,350,679
73,355,513
what atomicity does compare_exchange_weak provide?
quote from https://en.cppreference.com/w/cpp/atomic/atomic/compare_exchange bool compare_exchange_weak( T& expected, T desired, std::memory_order success, std::memory_order failure ) noexcept; Atomically compares the object representation (until C++20)value representation (since C++20) of *this with that of expected...
Because expected and desired are all of type T, so read & write operation on these values are not atomic That's true. The load of expected (and the store, if it happens) is not an atomic operation. Therefore, if this call to compare_exchange_weak is potentially concurrent with any other operation that accesses expect...
73,350,721
73,350,835
How to make destructor wait until other thread's job complete?
I have one main thread that will send an async job to the task queue on the other thread. And this main thread can trigger a destroy action at any time, which could cause the program to crash in the async task, a piece of very much simplified code like this: class Bomb { public: int trigger; mutex my_mutex; }; ...
In code, my comment looks like this : #include <future> #include <mutex> #include <iostream> #include <chrono> #include <thread> // do not use : using namespace std; class Bomb { public: void f1() { m_future = std::async(std::launch::async,[this] { async_f1(); }); } p...
73,352,462
73,352,799
Can a template function taking class object instantiate that object with it's constructors arguments?
Let's say I have a template function taking a class object: template<class T> void Foo(T obj); and a class definition as follows: class Bar { public: Bar(int a, bool b): _a(a), _b(b) {} private: int _a; bool _b; }; Is there a way to make the following code compile? Foo<Bar>(5,false); Foo<Bar>({5,false});...
Yes, this can be done with variadic templates and forwarding, and has many standard examples, like std::make_unique. In your case it would be: template<class T, class ...Args> void Foo(Args &&...args) { T obj { std::forward<Args>(args)... }; // use obj }
73,353,152
73,357,934
Why can std::move_iterator advertise itself as a forward (or stronger) iterator, when it dereferences to an rvalue reference?
According to cppreference, std::move_iterator sets its ::iterator_category to the category of its underlying iterator1. But I reckon it can be an input/output iterator at best, since for forward iterators reference must be an lvalue reference, while move_iterator sets reference (and the return type of operator*) to an ...
On one hand, the cppreference article on forward iterator requirements was wrong (already fixed by someone). reference must be any reference (& or &&), not specifically lvalue reference (&). Meaning move_iterator does conform. But on the other hand, auto-determining ::iterator_category uses different wording, which onl...
73,353,164
73,405,716
How to create a menubar in SFML application?
I'm trying to write an SFML 2.5.1 programm, but I have faced an issue, I can't find in the internet how to create working programm menubar, witch is located upper window (or upper screen in Mac OS), something like this: All I have found in the internet is a Titlebar, only first two options in menubar: File and Edit, a...
You can hide the original title bar and make your own using classes (button or titlebar_button, call it as u want) which is just a rectangle shape with the on_Click function. https://en.sfml-dev.org/forums/index.php?topic=24051.0 - Answer https://www.sfml-dev.org/documentation/1.6/namespacesf_1_1Style.php - Style docum...
73,353,235
73,356,076
Qt , how to create QApplication without argc and argv
Hey so I need to export a qt application as a .dll and , so I dont want any arguments like argc and argv , but QApplication needs them , so i tried this int main() { int c=1; char** v = (char**)("ApplicationName"); QApplication app(c,v); MainWindow window; window.show(); return app.exec(); } bu...
Try this: int main() { char* args[] = { (char*)"AppName" }; QApplication app(1,args); MainWindow window; window.show(); return app.exec(); }
73,353,308
73,354,501
Asynchronous Destruction and RAII in C++
According to RAII when I destroy the object, its resources are deallocated. But what if the destruction of the object requires asynchronous operations? Without using RAII I can call close method of my class that will call necessary async operations and will keep shared_ptr to my object (using shared_from_this) in order...
An object o to be asynchronously destroyed with respect to the thread, T, in which it was created cannot itself be managed via RAII, because destruction of stack-allocated objects is inherently synchronous. If o is managed via the RAII model then thread T will execute its destructor when the innermost block containing...
73,353,459
73,353,577
C++ standard conforming method to assign address of program memory to pointer
How to assing internal process memory address to pointer object in C++ via standard conforming method? For example, this is Undefined behavior, coz its dont defined in C++ Standard: CInterpretator* pInterpretatorObj= reinterpret_cast<CInterpretator*>(0x1000FFFF); or this, without reinterpret_cast, but with same effect...
There is no standards-compliant way of doing this. Standard C++ does not have a notion of memory layout, nor of particular integers being meaningful when casted to pointers (other than those which came from casting pointers to integers). The good news is, “undefined behavior” is undefined by the standard. Implementatio...
73,353,503
73,355,194
How to decode a picture converted to base64 using CryptStringToBinary?
My doubt is about how to use the value returned by the API to reconstruct the image. Also, does the way I'm creating the Bitmap preserve the picture transparency? Gdiplus::GdiplusStartupInput gdiplusStartupInput; ULONG_PTR gdiplusToken; Gdiplus::GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL); LPCWSTR base64...
My doubt is about how to use the value returned by the API to reconstruct the image. You are calling CryptStringToBinary() only 1 time, to calculate the size of the decoded bytes. You are even allocating memory to receive the decoded bytes. But, you are not actually decoding the base64 string to produce the bytes. ...
73,353,632
73,353,746
Is there a way to create a data type that can holds both integers and strings in C++?
Is there a way to create a data type that can holds both integers and strings in C++? For example, create a data type with name sti that I can define both integers and strings variables with it: sti a = 10; //this is integer sti b = "Hello"; //and this is string
You can use std::variant to achieve this which is C++17 feature. Refer this link to know more. Following is code sample. See it working here: #include <iostream> #include <variant> #include <string> int main() { using sti = std::variant<int, std::string>; sti a = 10; sti b = "Hello"; std::cout<<std::ge...
73,353,669
73,353,716
C++ Template class member function that returns the same template class data type
I'm trying to make a proof-of-concept class template that makes a 2D vector. I'm trying to make a member function that returns a "flipped" version of the vector were x becomes y and vice versa. I want the function to return the Vector2 template class data type. This is my syntax: Class: template<class T> class Vector2 ...
You are trying to define a member function named getFlippedCopy but you haven't declared such a function. I suspect that you've made a mistake by instead declaring a free friend function with the same name. I suggest making it a member function instead, which should then be const qualified: template<class T> class Vect...
73,353,689
73,353,781
Segmentation fault (core dumped) not able to debug the code for binary search with duplicates problem?
the problem is to return the lowest index of the element on a sorted list with duplicates. but my code is giving segmentation error.I am not able to identify the error in code. int binary_search(const vector<int> &a, int left, int right, int x) { // write your code here if (right - left == 0) return rig...
When you find the result a[mid] == x, store it & keep searching to the left portion for the lowest index. int binary_search(const vector<int> &a, int left, int right, int x) { // write your code here if (right - left == 0) return right; int idx = -1; while (right >= left) { int mid ...
73,354,202
73,354,295
Why does the pointer exist even after the unique_ptr to which the pointer is assigned goes out of scope?
I recently started learning about smart pointers and move semantics in C++. But I can't figure out why this code works. I have such code: #include <iostream> #include <memory> using namespace std; class Test { public: Test() { cout << "Object created" << endl; } void testMethod() { ...
You do not need a std::unique_ptr to write code with the same issue int main(int argc, char *argv[]) { Test* testPtr = new Test{}; delete testPtr; testPtr->testMethod(); // UNDEFINED !!! return 0; } The output is the same as yours here https://godbolt.org/z/8bocKGj1M, but it could be something el...
73,354,331
73,369,231
when using ImGui with Glut it does not show any objects
I'm coding a rendering engine in C++ with OpenGL and GLUT and trying to integrate ImGUI into my engine, but I have a problem. it either renders the gui and only the background (no objects), or it only renders the objects and background (no GUI). This code: glutDisplayFunc(renderScene); glutIdleFunc(renderScene); glutRe...
The problem is that GLUT callback handlers in both of your examples are set both manually (glut...Func) and by ImGui via ImGui_ImplGLUT_InstallFuncs. The latter sets default ImGui handlers for many GLUT callbacks (see the source), in particular glutReshapeFunc is used to set current window resize callback to ImGui_Impl...
73,354,972
73,355,028
How to cross link libraries in CMake
In a c++ CMake project I have an executable main and two libraries lib1 and lib2. A function in lib1 needs a function from lib2 and visa versa. Also, lib1 only contains .h files. The main executable will use both libraries. When I try and "make" the project, I get an error: error: redefinition of ‘void lib1()’. The fi...
I dont think it's anything related to cmake. Although convoluted (I'd do it in another way but hey it's your code) I think you are defining the body of a function in lib1 where it should reside in a cpp file. Make that function lib1 inline. inline void lib1() { ... } or alternatively defined it in the header and impl...
73,355,092
73,383,655
How to convert/use the run time variable in compile time expression?
I have the following situation (live code : https://gcc.godbolt.org/z/d8jG9bs9a): #include <iostream> #include <type_traits> #define ENBALE true // to enable disable test solutions enum struct Type : unsigned { base = 0, child1, child2, child3 /* so on*/ }; // CRTP Base template<typename Child> struct Base { void ...
Since you are restricted to C++11 and are not allowed to use external libraries such as boost::variant, an alternative would be to reverse the logic: Do not attempt to return the child type but instead pass in the operation to perform on the child. Your example could become this (godbolt): #include <iostream> #include ...
73,355,369
73,358,075
What does (import) in .wat mean?
The Problem I have been fiddeling around with wasm all day, now (import $import0 "env" "_Znaj" (param i32) (result i32)) popped up in my .wat. And it breaks my code. The Error Message The exact error I get is: Uncaught (in promise) LinkError: import object field '_Znaj' is not a Function JavaScript implementation Th...
_Znaj. Is the array allocator used by the new operator when creating new arrays. At least some compiler do it that way. And whatever the compiler was you used it did the same. This _Znaj is then linked dynamically or statically. In this case it is dynamic for whatever reason but on most online WASM compilers it is put ...
73,355,546
73,356,425
Error passing Eigen matrix to a function in C++: "no instance of overloaded function matches the argument list"
I have a script that is working fine, but when I try to write a function with the same script I get the error "no instance of overloaded function "aapx" matches the argument list". I know that an Eigen::Matrix should always be passed by reference to a function so I did and I thought maybe the issue is I am initializing...
Your third argument, ph needs to be Eigen::Ref<const Eigen::MatrixXcd> ph (without the reference) and not Eigen::Ref<const Eigen::MatrixXcd>& ph because ph is already a reference. You do not want to change the reference, you want to change the matrix. Check out this answer: Correct usage of the Eigen::Ref<> class
73,355,569
73,355,641
Extract data from templated derived class using virtual base class function
I have a Device object that can have 1 or more State objects. I do not want to limit what sort of state the State objects can describe so I've templated the value of the State objects. Since I want each Device to keep a collection of these State objects, I've derived them from a GenericState class. I'd like to be able ...
My - maybe opinionated - observation is that people overuse virtual, maybe because of how C++ is usually taught. virtual is very useful if you have to provide 30-years forward compatibility and module load without restart in a telco system; it's less useful when concrete types are known, esp. when you recompile the ent...
73,355,693
73,355,870
How to pass raw pointer of unique_ptr to a function that takes in unique_ptr?
#include <iomanip> #include <iostream> #include <memory> #include <string> #include <type_traits> #include <utility> class Res { std::string s; public: Res(std::string arg) : s{ std::move(arg) } { std::cout << "Res::Res(" << s << ");\n"; } ~Res() { std::cout ...
instead of passing the address with get() you must release the ownership with release() void api_fun(std::unique_ptr<Res> const&); void fun2(std::unique_ptr<Res>& uniq_ptr){ api_fun(uniq_ptr); std::cout << uniq_ptr.get() << '\n'; } void fun1(Res* ptr){ std::unique_ptr<Res> tt(ptr); fun2(tt); tt.release(); }...
73,355,758
73,355,804
Why does default constructor only work with class pointers?
I've been messing around with a default constructor example inspired by this answer. This one works fine: class Foo { public: int x; Foo() = default; }; int main() { for (int i = 0; i < 100; i++) { Foo* b = new Foo(); std::cout << b->x << std::endl; } But when I try this out with a...
It's because x is uninitialized. Reading uninitialized variables makes your program have undefined behavior which means it could stop "working" any day. It may also do something odd under the hood that you don't realize while you think everything is fine. These all zero-initialize x: Foo* b = new Foo(); Foo* b = new Fo...
73,355,940
73,644,905
Removing the desired access from the pre operation routine in kernel mode, leaves the process in eternal suspension
I am new to kernel and c++ development, but I am trying to develop a handler test in which the PROCESS_SUSPEND_RESUME flag of OperationInformation->Parameters->CreateHandleInformation.DesiredAccess can be removed in the pre-operation routine for a specific process (notepad.exe ) if (OperationInformation->Operation == ...
I found an easy solution. Simply run notepad.exe and then instruct kernel driver to remove these flag (0x0800). Notepad.exe could not be suspended or resumed
73,356,262
73,357,095
C++ Why are my Objects being destroyed, and sometimes twice in a row when using range based for loop
I'm a beginner programmer looking to understand why my objects are being deleted, sometimes even twice. I'm trying to avoid creating them on the heap for this project as that is a more advance topic I will try at a later time. Whats causing the book1, book2 etc.. objects to be instantly deleted? Also it outputs the sam...
As per the various suggestions in the comments I have compiled the program to suit your needs. It will work without any unwanted allocations. Changes I made are: 1.Reserving the vector to 5 elements. 2. Emplacement. 3. Passing the vector as a reference to the function and 4. Taking the vector elements as a reference w...
73,356,618
73,431,607
How should I configure clangd to make it scan the library I download with CMake FetchContent?
I use CMake FetchContent to download nlohmann/json. But my clangd doesn't scan the library after downloading. So how should I configure my clangd? my CMakeLists.txt: cmake_minimum_required(VERSION 3.11) project(ExampleProject LANGUAGES CXX) include(FetchContent) FetchContent_Declare(json URL https://github.com/nlohma...
Now I know how to solve this problem. When using CMake, set CMAKE_EXPORT_COMPILE_COMMANDS to 1, to make CMake generate the file compile_commands.json. Clangd will automatically scan this file and follow it to scan for third-party libraries.
73,356,755
73,356,819
Is it necessary to avoid memory leak when returning pointer by using shared_ptr?
I have two functions for converting char array from gb2321 to utf-8 like, #include <windows.h> #include "memory.h" #include <wchar.h> #include <iostream> using namespace std; //GB2312 to UTF-8 char* G2U(const char* gb2312) { int len = MultiByteToWideChar(CP_ACP, 0, gb2312, -1, NULL, 0); wchar_t* wstr = new wc...
Instead of managing a raw pointer, or even a shared_ptr to manage a char pointer, you can simply use std::vector. It has a constructor that accepts a size and a value (thus you don't need memset). You can use std::vector::data to access the underlying data buffer. Below you can see an example for str. A similar soluti...
73,356,985
73,374,648
C++ Restricting variable type to multiple base classes
Consider the following classes: class A {}; class B {}; class C {}; class D : public A, public B, public C {}; class E : public A, public C {}; class F : public A {}; I want to write a variable type that only accepts types which derive from both A and B (in this case only D) so that the following hold: T var; var = D...
You Here is a type that references (points to) an object that derives from both A and B. The simplest barebones version is struct AB { A* a; B* b; template <class D> AB(D* d) : a(d), b(d) {}; template <class D> AB& operator=(D* d) { a=d; b=d; return *this;} }; Now you can have: D d; E e; AB ab1(&d); // OK AB a...
73,357,204
73,357,231
Why do we use this-> inside constructor of C++ and not this.(DOT)
Rectangle::Rectangle(Rectangle &r) { this.length=r.length; this.breadth=r.breadth; } I used this. instead of this-> and it gives error [Error] request for member 'breadth' in '(Rectangle*)this', which is of pointer type 'Rectangle*' (maybe you meant to use '->' ?) So does this mean class are sort of like Pointe...
According to docs: The expression this is an rvalue (until C++11)a prvalue (since C++11) expression whose value is the address of the implicit object parameter So, this here is a pointer that point to the address that store value of the instance of class Rectangle.
73,357,455
73,497,119
How to correctly use the update() clause in OpenMP
I have a program that was originally being executed sequentially and now I'm trying to parallelize it via OpenMP Offloading. The thing is that when I use the update clause, depending on the case, if I include the size of the array I want to move it returns an incorrect result, but other times it works. For example, thi...
Well I don't know why anyone from OpenMP answered this question, as the answer was pretty simple (I say this because they don't have a forum anymore and this is supposed to be the best place to ask questions about OpenMP...). If you want to copy data dynamically allocated using pointers you have to use the omp_target_m...
73,357,492
73,357,576
How to initialize the LeastMaxValue template param in counting_semaphore?
I have a use case where I need to use counting_semaphore as a data member in a class. If it were a global variable, I could've omitted the template argument, and it would've been default initialized. But as mentioned here, in case of a member variable, the template argument needs to be specified, and in our case it has...
Ideally, you would look at how the data member will be used and determine an upper bound on what the semaphore needs to count. This upper bound is an appropriate LeastMaxValue. It is not always possible to find such a bound, though. If you have no way of bounding the maximum the data member needs to handle, you could u...
73,357,515
73,357,579
To check if there are any a and b that satisfy the given equation
Problem You are given a positive integer X. Your task is to tell whether there exist two positive integers a and b (a > 0, b > 0) such that 2⋅a+2⋅b+a⋅b=X If there exist positive integers a and b satisfying the above condition print YES, otherwise print NO. Input Format The first line of input will contain a single int...
Take a flag variable and set to true if consition is satisfied.Print it after the loop not inside the loop #include <iostream> using namespace std; int main() { int t,x,i,j; int flag; cin>>t; while(t--) { cin>>x; flag = checkSatisfiedNumber(x) if (flag == 1) cout<<"Yes"<<endl; ...
73,357,632
73,358,595
Limit chunks of combination in c++
I modified a code I've found on the internet to fit my needs. It calculates and prints all possible combinations of r elements in an array given size of N. Here's the code: #include <iostream> #include <vector> void combinationUtil(std::vector<int> arr, std::vector<int> data, int start, int end, int index, int r); vo...
I solved the issue by modifying another combination method I found on this site. Here's the code for it: #include <iostream> #include <vector> using namespace std; vector<int> people; vector<int> combination; void pretty_print(const vector<int>& v) { static int count = 0; cout << "combination no " << (++count) <...
73,357,915
73,358,303
How to debug a dll using Visual Studio?
How can I debug a dll using visual studio? I have the DLL source, pdb, etc. I tried these options: BOOL APIENTRY DllMain( HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved ) { void DebugBreak(); switch (ul_reason_for_call) { ...
The quickest way to fix this is via the Modules Window in the Debugger: Put a breakpoint after your LoadLibrary call. Go to Debug->Windows->Modules in the menu bar to bring up the Modules window. Search for your dll file in the list. In the Symbol Status column it should read "Cannot find or open the PDB file". Rig...
73,358,448
73,369,784
Boost Log + Log rotation in another folder
is there a possibility, to write with Boost Log the history log files in another folder than the current log file? log trace_2.log history trace_0.log trace_1.log I'm using an asynchronous sink and tried it via set_file_collector, but all logs are written to /tmp/log folder and when after closing the applicatio...
I found the solution. The configuration was not correct, so the settings enable_final_rotation = false does not worked on my side. Because of this, with each program exit, the current log file was moved to the history folder, also if it does not reached the rotation size. I forgot this information in the post. This con...
73,359,216
73,359,310
How to return nothing from an integer function in C++?
Consider the following code: #include <iostream> int test(int a){ if (a > 10){ return a; } else{ std::cout << "Error!"; return nothing; } } int main(){ std::cout << test(9); return 0; } What I want is that The integer function test(int a), return a if a > 10, otherwise r...
#include <stdexcept> int test(int a){ if (a > 10){ return a; } else{ throw std::invalid_argument( "a is smaller or eq than 10" ); } }
73,359,293
73,359,861
brute force approach for union of two array
I wanted to apply brute force to find the union of two arrays and theoretically it should works but for some reason only first array goes into 3rd array(3rd array is for storing elements form array 1 and array2) and size of 3rd array is getting increased from 8 to 12 //find the union of two arrays #include<iostream> #i...
You have 2 issues: First one, initialization of arr3 std::vector<int> arr3(n+m); // create a vector of SIZE n+m (with value 0) it should be std::vector<int> arr3; arr3.reserve(std::min(n, m)); // "optimization" to avoid future allocation Second one is your last if(count==1) { arr3.push_back(arr1[i]); } which a...
73,359,351
73,360,017
Why does my second 3D object not have four faces in Open GL
As the title says I'm tyring to model a simple giraffe out of arraycubes in open GL wiht C++, now I got the concepts done, but ran into an issue, when I start on the neck for some reaosn I lose 5 out of the 6 faces of my cube, the example I'm following doesn't result in this. I linked a small video below to show the vi...
For the second object (the neck) you apply a scale transformation on x that scales the x component of all the following drawn vertices to 0.0: glScalef(0.0, 0.5, 0.25); That 0.0 should've probably been a 1.0. That's the reason you only see one quad in the render video: That's the quad/face (actually two faces) which st...
73,359,977
73,360,722
Why some C++ standard functions are missing literal exception specification or not marked as conditionally noexcept?
I've noticed that some standard functions having a wide contract such as functions in [iterator.range] conditionally do not throw exceptions, but they are not marked as conditionally noexcept. EDIT: It is described in this paper: Each library function having a wide contract, that the LWG agree cannot throw, should be ...
Here is a paper (quoted by some other standard library proposals) for reasons to not specify noexcept on some standard library functions: N3248: noexcept Prevents Library Validation If a function that the standard says does not throw any exceptions does throw an exception, you have entered undefined behaviour territory...
73,360,200
73,360,246
Why is C++ implicitly converting 0.0 to some extremly small 'random' value?
I'm trying to compare two class objects, which has both been initialized with 0.0, but for some reason C++ decides to convert the 0.0 to some extremly small value instead of keeping the 0.0, which makes the comparison fail as the value it converts to is not always exactly the same. Vector.cpp #include "Vector.h" // op...
Your Vector class never initializes the x and y members. Since the member variables are uninitialized, they will have an indeterminate value, which you should look at like it was random or garbage. Using indeterminate values of any kind in any way, leads to undefined behavior. To initialize the member variables, use a ...
73,360,380
73,360,869
Why does this innocent function cause a segfault?
I'm trying to code metaballs in C++/SFML, my program works just fine in a single thread. I tried to write an MRE to find the problem and here's what I got: main.cpp // main #include <iostream> #include "threader.h" float func(float x, float y, float a, float b, float r) { return 1.f / sqrt((x - a)*(x - a) + (y - ...
Rather than try to draw to the window on multiple threads, I would instead use std algorithms to filter the points to draw circles, and draw them all on the main thread. std::vector<std::pair<int, int>> getPoints(const sf::RenderWindow& window) { std::vector<std::pair<int, int>> points; for (int X = 0; X < wind...
73,361,084
73,361,114
What is the best way to convert int to double in C++?
I know that convert int to double in C++ has many ways. but what is the best way for do this?
Use static_cast<double>(expression). In general, it is recommended to use C++ ways of casting (static_cast, dynamic_cast), instead of the old C-style casting, such as (double)int, (int)double.
73,361,992
73,362,114
How to customize vcxproj generation by CMake
I want to use CMake to generate .vcxproj files. Then I open specific project/solution and work in VS as usual. How do I customize default configurations, generated by VS generator? In particular, how do I specify in my cmake files (whatever it should be) that I need release runtime for "Debug" configuration? (i.e. /MD ...
In particular, how do I specify in my cmake files (whatever it should be) that I need release runtime for "Debug" configuration? (i.e. /MD instead of /MDd). This will work: set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreadedDLL" CACHE STRING "MSVC runtime library selection") Then all of the targets you build in all co...
73,362,269
73,362,356
how do i link wininet library with cmake
This is c++ code to get IP address (main.cpp) (project -> Prueba2 ). #include <iostream> #include <windows.h> #include <wininet.h> std::string real_ip() { HINTERNET net = InternetOpen("IP retriever", INTERNET_OPEN_TYPE_PRECONFIG, NULL, ...
You can use target_link_libraries: ... add_executable(Prueba2 main.cpp) target_link_libraries(Prueba2 wininet)
73,362,438
73,363,905
Problem with linking Boost 1.79 libs, builded with MinGW GCC, with CMake on Windows
I'm using Boost 1.79 and Windows 10. For building Boost libs I use TDM MinGW. After trying to build my test program with CMake, I get next error: CMake Error at D:/CMake/share/cmake-3.24/Modules/FindPackageHandleStandardArgs.cmake:230 (message): Could NOT find Boost (missing: log thread) (found suitable version "1....
Well, I solve my problem by setting Boost_DEBUG to ON. After analyzing debug info it became clear that the problem was two empty variables: Boost_COMPILER and Boost_ARCHITECTURE. And to solve the problem i just set these variables by looking at the full filename, for example: We have filename libboost_log-clang14-mt-x3...
73,362,585
73,362,622
C++ override specifier without virtual? Does override imply virtual?
Linked question is not the same - and does not even mention override Edit: The new list of duplicates contains one legitimate duplicate, which I did not find from search. I was not aware prior to asking this that the choice of whether or not to use virtual in derived class members was going to be a contentious issue fo...
The answer you're looking for is in https://en.cppreference.com/w/cpp/language/virtual If some member function vf is declared as virtual in a class Base, and some class Derived, which is derived, directly or indirectly, from Base, has a declaration for member function with the same name parameter type list (but not th...
73,363,252
73,365,285
6-bit CRC datasheet confusion STMicroelectronics L9963E
I’m working on the SPI communication between a microcontroller and the L9963E. The datasheet of the L9963E shows little information about the CRC calculation, but mentions: a CRC of 6 bits, a polynomial of X6 + X4 + X3 + 1 = 0b1011001 a seed of 0b111000 The documentation also mentions in the SPI protocol details ...
Bit ranges in datasheets like this are always inclusive. I suspect that this is just a typo, or the person who wrote it temporarily forgot that the bits are numbered from zero. Looking at the other bit-field boundaries in Table 19 of the document you linked it wouldn't make sense to exclude the bottom bit of the data f...
73,363,327
73,364,020
boost program-options uses deprecated feature
I have boost-program-options version 1.78 installed via vcpkg. When I compile with clang++ and -std=c++20 I get the following errors. This doesn't happen when I compile with g++. According to this this std::unary_function is deprecated as of C++11. In file included from /home/david/C/vcpkg/installed/x64-linux/include/b...
The use of std::unary_function has been replaced for compilers/standard libraries not supporting it anymore since Boost 1.64 for MSVC (commit) and since 1.73 for other compilers (commit). But it continued using std::unary_function as default as long as it was not detected as removed. Since Boost 1.80 the use of std::un...
73,364,145
73,364,218
Forbidden syntax for pointer/reference to bound member function
Suppose I have the following: struct A { int foo(int bar) const { return bar; } }; and I want to specify a name that refers to a "bound" member function (i.e.): A a; auto opt1 = a.foo; // Forbidden, instead do something like... auto opt2 = [&a] (int i) { return a.foo(i); }; // or ... auto opt3 = std::bind(&A::foo, a...
[expr.ref]: [for the expression E1.E2]....if E1.E2 refers to a non-static member function...The expression can be used only as the left-hand operand of a member function call.