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,728,093
70,728,505
Cuda device memory variables with OpenMP multithreading produce wrong results
I have a function in which I am calling a cuda kernel serially in a loop. This function is executed parallely in threads using OpenMP. Through each iteration, I update a variable currentTime with: cudaMemcpyFromSymbolAsync(&currentTime, minChangeTime, sizeof(currentTime), 0, cudaMemcpyDeviceToHost, stream_id); where m...
When multiple reduction kernels run simultaneously, there is a race- condition with the global variable minChangeTime. You need to have separate device memory for each kernel that should run in parallel. The simplest approach would be to just cudaMalloc minChangeTime in each thread instead of declaring it a global vari...
70,728,149
70,728,336
Homework Beginner C++: Unable to perform Type Casting during addition of integers
In order to help us understand type casting in C++, we are required to perform addition of two int's as shown below. If we provide two int's as 4 and 5 respectively, the output should be 4 + 5 = 9. I tried to follow this type casting tutorial without any success. Could someone please provide me a hint or something? Quo...
if you typecast a character or string it get's converted into its equivalent ASCII value , either you need to use stoi or subtract from '0' for every digit position(a bit repeatitive work) go with stoi
70,728,570
70,735,443
Why cpplint doesn't care about indentation/spaces and what is the alternative?
This is my C++ code: int f() { return 1 + 2; } I'm trying to run it through cpplint: $ cpplint src/f.cpp Done processing src/f.cpp No errors found. What am I doing wrong? Cpplint really does think that this code is properly formatted? If this is really the case, which style...
Cpplint only checks a few special indentation cases, it is not a complete style checker. The cause for this is that cpplint does not property parse files, but checks files line-by-line using regular expressions. That makes it hard to write certain checks for issues that require reasoning about Multi-Line contexts. So c...
70,728,874
70,728,932
Template classes circular dependency issue (c++)
I wanted to implement an observer pattern for an event system, but the compiler gives me a bunch of errors and I'm currently not able to fix them. I have two templated class in two different headers, a listener and a event dispatcher and both needs to store pointers to the other class. In Dispatcher.h //Dispatcher.h ...
You can solve this problem of circular dependency by removing the #include "Listener.h" from Dispatcher.h and instead adding a forward declaration for class template Listener<> as shown below: Dispatcher.h #pragma once #include <vector> //no need to include Listener.h //forward declaration template<typename T> clas...
70,729,275
70,730,391
How to use a constructor variable in the operator() function?
I'm trying to call a variable which is declared in the constructor in the operator() function. Variable is declared of type boost::multi_array<float, 2>. But still it throws the error: error: no match for ‘operator /’ I guess boost library has these predefined operators! Can anyone see what I'm doing wrong here? #ifn...
You can do something like this: /* Characteristic function */ #ifndef CORRELATOR_CHARACTERISTIC_FUNCTION_HPP #define CORRELATOR_CHARACTERISTIC_FUNCTION_HPP #include <halmd/numeric/blas/fixed_vector.hpp> #include <cmath> #include <boost/multi_array.hpp> #include <complex> #include "read_box.hpp" namespace correlator ...
70,729,425
70,731,008
Initialize std::vector with given array without std::allocator
I am using an external library which provides a function with the following interface: void foo(const std::vector<int>& data); I am receiving a very large C-style array from another library which has already been allocated: int* data = bar(); Is there any way for me to pass on data to foo without allocating and copyi...
Magic This answer is magic, dependent on the implementation of the compiler. We can forcibly access the container of a vector. Take g++ as an example. It uses three protected pointers, _M_start, _M_finish, and _M_end_of_storage to handle storage. So we can create a derived class that sets/resets the pointers to the ret...
70,729,666
70,729,784
When to use c or cpp to accelerate a python or matlab implementation?
I want to create a special case of a room-impulse-response. I am following this implemetation for a room-impulse-response generator. I am also following this tutorial for integrating c++\c with python. According to the tutorial: You want to speed up a particular section of your Python code by converting a critical se...
Why use C++ to speed up Python C++ code compiles into machine code. This makes it faster compared to interpreter languages (however not every code written in C++ is faster than Python code if you don't know what you are doing). in C++ you can access the data pointers directly and use SIMD instructions on them to make t...
70,729,816
70,729,876
Can a braced initializer be used for non-type template argument in C++?
In the next program the second non-type template argument of struct A is initialized with {} in the alias template B<T>: template<class T, T> struct A{}; template<class T> using B = A<T, {}>; B<int> b; GCC is the only compiler accepting this. Both Clang and MSVC reject the program with similar errors. Clang: error: ...
I'd say GCC is wrong. The grammar for template-argument in [temp.names] says that a template argument must either be a constant-expression, a type-id or an id-expression. {} is neither an expression, nor a type, nor an (un)qualified name.
70,730,831
70,735,005
What's the mathematical reason behind Python choosing to round integer division toward negative infinity?
I know Python // rounds towards negative infinity and in C++ / is truncating, rounding towards 0. And here's what I know so far: |remainder| -12 / 10 = -1, - 2 // C++ -12 // 10 = -2, + 8 # Python 12 / -10 = -1, 2 // C++ 12 // -10 = -2, - 8 # Python 12 / 10 = 1, 2 ...
But why Python // choose to round towards negative infinity? I'm not sure if the reason why this choice was originally made is documented anywhere (although, for all I know, it could be explained in great length in some PEP somewhere), but we can certainly come up with various reasons why it makes sense. One reason i...
70,731,072
70,731,138
Printing variable value using Reference to const gives different result
I am learning about references in C++. So i am trying out different examples to better understand the concept. One example that i could not understand is given below: double val = 4.55; const int &ref = val; std::cout << ref <<std::endl; //prints 4 instead of 4.55 I want to know what is the problem and how can i ...
The problem is that the reference ref is bound to a temporary object of type int that has the value 4. This is explained in more detail below. When you wrote: const int &ref = val; a temporary of type int with value 4 is created and then the reference ref is bound to this temporary int object instead of binding to the...
70,731,559
70,731,703
How can I pass a class method as a parameter to another function and later call it, preferably making the variable class method signature explicit?
If I have a class that needs to call a parent class method with a class method as parameter I can do it with std::function + std::bind as shown below: class A { void complexMethod(std::function<void()> variableMethod) { // other stuff ... variableMethod(); // some other stuff.. } } clas...
How would I need to change the above code to implement the same thing using templates instead of std::function + std::bind? And how about lambdas instead of std::function + std::bind? I still want to call B:myWay() and B::otherWay() but using lambdas. I don't want to substitute B:myWay() and B::otherWay() with lambdas...
70,731,687
70,762,042
How can I integrate QML MediaPLayer with C++ side
I have developed a QML based video player program using MediaPlayer element. The program has most of basic functionality of a video player(play,pause,vol up/down,forward,bakcward etc.). My next task is add subtitle to a video and I need to use metaObject method of MediaPlayer element but QML side does allow that funtio...
This will depend on how exactly you launch the QML application. Suppose it is set up like this: int main(int argc, char **argv) { // Q(Gui)Application setup... QQmlApplicationEngine engine; engine.load(QUrl("qrc:/main.qml")); // ... } And somewhere inside the QML object hierarchy you have a MediaPlay...
70,732,250
70,736,813
Setting the size of array in a struct by passing as a const to a function - Non-type template argument is not a constant expression
User sets k at running time. This number will be constant for the rest of the code. I want to create a function to pass and create a struct that includes an array of size k with that number. However, the compiler returns this error: Non-type template argument is not a constant expression Any recommendation will be app...
A fundamental principle about templates is that: Any template argument must be a quantity or value that can be determined at compile time. This has dramatic advantages on the runtime cost of template entities. But in your example, k is not a compile time constant and you're using it as a template argument and so as a...
70,732,298
70,733,432
QML Update Gridview from QML or C++ without emit dataChanged
I have a QAbstractListModel, which is tied to QML via engine.rootContext()->setContextProperty which is displayed in a GridView. It contains cards like Aces, Queens etc. I would like to sort the cards in different ways (like color, type etc). The sorting fuction can be called via qml: GridView { id:table_player ...
Is Deckmodel the same thing as Playerfield in your code? When changing your model, you need to call begin/endResetModel(). That will automatically emit the appropriate signals so your QML should update correclty. void Deckmodel::sortDeck() { beginResetModel(); for(uint a = 0; a < cards.size(); a++) { ...
70,732,683
70,732,858
How to add blank lines between definitions?
I successfully managed to make clang-format format my code like iIwant. However, there is one thing that bugs me: I want a blank line between definitions of structs/classes/functions and between declarations of functions. Currently, when formatting, clang-format removes blank lines, which makes everything condensed. He...
You have MaxEmptyLinesToKeep: "0" which needs to be set to 1 instead, to ensure that multiple empty lines between definitions are not removed. Importantly, the value needs to be an unsigned type, not a string. So the correct setting for what you want should be MaxEmptyLinesToKeep: 1 Note that this won't work if you ...
70,732,979
70,732,995
Is using headers multiple times bad?
Lets say I am using header guards, #ifndef MAIN_H #define MAIN_H #include "foo.h" #include "some_header_file.h" ... // Some Code #endif Inside foo.h file also with Header guards. #ifndef FOO_H #define FOO_H #include "some_header_file.h" ... // Some Code #endif As you can see main file have 2 headers one of...
Does Header guards prevent duplicate header files? Yes. The first encountered inclusion will bring the content of the header to the translation unit, and the header guard causes successive inclusions to be empty which prevents the content of the header from being duplicated. This is exactly the reason why header guar...
70,733,043
70,733,123
bitwise operation xor mask
I'm sorry if this seems like a stupid question I'm just having trouble understanding bits and bitwise operation assignment I have two integers one is a mask and the other is arbitrary and I'm supposed to xor the integer with the 16 most significant bits of the mask but I'm not exactly sure if significant is the first 1...
For an unsigned 8-bit value, you might have: Bit number: 7 6 5 4 3 2 1 0 Bit value: 1 0 0 0 1 1 0 1 = 141 = 0x8D The 4 most significant bits (MSB) are bits 7-4; the 4 least significant bits (LSB) are bits 3-0. You'd extract the 4 most significant bits from uint8_t x8 = 141; using: ...
70,733,262
70,733,946
Template function specialization for specific template ( not type )
I have some templated class types like A,B,C as follows: template < typename T > class A{}; template < typename T > class B{}; template < typename T > class C{}; And now I want to have a function which accepts in general any type like: template < typename T> void Func() { std::cout << "Default " << __PRETTY_F...
It feels a bit complicated to me. Can that be simplified? Would be nice if the Check template can be removed. Any idea? Much of complexity and in-elegance is in the fact you need a new concept for every class template. Write a general-purpose and reusable concept, and it is no longer complicated to use. template <typ...
70,733,508
70,736,286
Linking up C++ and Python
I am trying to set up a program in Visual Studio where I link up a C++ file and a Python file. The printing statement from the Python statement still outputs and I am able to change it. However, whenever I run the program my console says: Start 1 2 00000000 File "C:\Users\marce\source\repos\PythonCPPSample\Release\setu...
This error message is appearing in the console application, but even if the printing statement were to be indented underneath the function in the setup.py it would not fix the problem. This is because the python file that it's linking to had not been pulled up from the correct release folder. So, I just had to look at ...
70,733,518
70,733,550
Why defining a variable inside a struct doesn't cause link errors?
struct foo{ int bar1 = 5; const static int bar2 = 6; }; Sharing foo using a header file among multiple translation units doesn't cause a link error for bar1 and bar2, why is that? To my knowledge, bar1 doesn't even exist until an instance of foo is created and each instance of bar1 will have unique symbol, so no...
Violations of The One Definition Rule do not require a diagnostic or a compiler error. Presuming that bar2 is referenced in some translation unit: some compilers may successfully compile and link the resulting code. Other compilers may not and reject it (presumably at the linking stage). The C++ standard indicates that...
70,733,545
70,733,692
finding top 10 elements in the hash table which contains 250,000 integer elements in C++
i want to find top 10 elements int the hash table. The hash table contains 250000 elements and these elements are only integer values. I dont want to sort the whole table. When i find the top 10 elements it is enough for me the rest is not important. What is the FASTEST(RUNTİME) way to do it? maybe heap sort? C++
I'll assume that the integers are in a collection you can iterate over. Imagine you need to find the single max element - you can iterate over the collection once keeping track of the largest element you have seen so far. Now modify the above approach for the top two elements you have seen so far. ... Now modify the ab...
70,733,643
70,733,710
gtest EXPECT_CALL does not working when expected call is nested
Look at such code snippet: class Foo { public: Foo() { } void invoke_init(const int i) { init(i); } private: void init(const int i) { std::cout << "init " << i << std::endl; } }; class MockedFoo : public Foo { public: MOCK_METHOD(void, init, (const int)); }; TEST(Foo, TestInitCalled) { ...
Foo::init needs to be protected instead of private. It also needs to be virtual. Without protected as its visibility attribute, it can't really be overridden in the inherited class. Without virtual, gmock can't do much with it either. Instead of this: private: void init(const int i) { std::cout << "init " << i ...
70,734,093
70,739,661
How to load ImGui image from byte array with opengl?
I am trying to render an image in my c++ ImGui menu; I believe the end code would be something like ImGui::Image(ImTextureID, ImVec2(X, Y));. I already have a byte array that includes the image I want to render, but don't know how to go about loading it into that ImTextureID that's being passed in. I have found how to ...
The 'ImTextureID' in ImGui::Image is simply an int, with a value corresponding to a texture that has been generated in your graphics environment (DirectX or OpenGL). A way to do so in OpenGL is as follows (I'm not familiar with DirectX but I bet that 'D3DXCreateTextureFromFileInMemoryEx' does pretty much the same): Ge...
70,734,791
70,734,925
C++ removing a element in string array which appears 5 times
Here is the code I have, I am having trouble finding a way to remove all Apple elem in the array. I am able to count the apples in the array. I hope someone can help... string items[10] = { "Apple", "Oranges", "Pears", "Apple", "bananas", "Apple", "Cucumbers", "Apple", "Lemons", "Apple" }; //Counts the t...
Some options you'd have would be: Walk your array of items and substitute your "Apple" strings for empty strings. Use a std::vector of strings and whether a) initialize it with the array of items and then call std::erase_if (C++20) to remove the "Apple" strings, or b) initialize it without elements and then call std::...
70,735,056
70,735,340
two arrays, find the missing numbers
Given two arrays, first has 'n' numbers and the second one has 'n-m' numbers; the second array is not in the same order as the first. If there are several numbers with the same value, they end up in the order of the positions in the original array. Also, all the values from the second array are also found in the first ...
Your program seems to be outputting the correct result. However, I felt that I need to refactor your code to improve its readability and remove the bad practices used in it. The below is the same as your code with a bit of improvement: #include <iostream> #include <array> #include <limits> int main( ) { std::arra...
70,735,301
70,735,746
Rcpp does not compile on Mac OS Monterey, R 4.1.2., clang error
Trying to get Rcpp to work on R 4.1.2 on Mac OS Monterey using an Intel computer. > library(Rcpp) > evalCpp("2 + 2") clang++ -mmacosx-version-min=10.13 -std=gnu++14 -I"/Library/Frameworks/R.framework/Resources/include" -DNDEBUG -I"/Library/Frameworks/R.framework/Versions/4.1/Resources/library/Rcpp/include" -I"/privat...
There is an old reference to a prior version of the clang compiler present. In R, please type: unlink("~/.R/Makevars") unlink("~/.Renviron") Please restart R and, then, try: Rcpp::evalCpp("1+1")
70,735,488
70,735,703
How to call a Python function from C++ on Ubuntu 20.04
I'm currently in a class where I'm asked to establish integration between Python and C++ as we will be working with both later in the class. My instructor has provided some simple C++ and Python code so we can test the integration and has also provided instructions on how to set this up using Visual Studio. I currently...
Add this in your main function after Py_Initialize(); PySys_SetPath(L".:/usr/lib/python3.8"); this is the search path for python module. Add . to search in the current path.
70,735,492
70,735,611
Inferring namespace of freestanding function
Question on namespace qualification: Why isn't the namespace of the function inferred below? namespace X { void func(int) {} struct Z{ void func(){ //func(int{}); does not compile X::func(int{}); // this works } }; } int main() { X::Z z; z.func(); }
This specific part of C++ can be generally called "unqualified name lookup". This term describes taking a single identifier in a C++ program and then determining which actual type, or object, or function, or class, it is referencing. For example, there can be many things called rosebud in a C++ program, so rosebud(); ...
70,736,140
70,738,597
Why does Qt Designer add so much space?
Why does Qt make so much space? How can I fix this? I just want to create two labels, two text boxes and a login button. I'm trying to make a login form. Something like this: Why does it need so much space to just have small buttons? This is the nicest I've been able to get it to look, but even this looks terrible.
Just add a Vertical Spacer to the top and the bottom, then you will have your expected result. If you would like to add it through the code and not in Designer, you would need to add it on the QLayout with QBoxLayout::addStretch(int stretch = 0) or QBoxLayout::addSpacing(int size), depending on your need
70,736,588
70,736,823
Why does MSVC's STL implementation cast to const volatile char* here?
I was looking through some of the standard library's implementation for the usual containers (vector, unordered_map, etc...) when I came across the following, in the xutility header: template <class _CtgIt, class _OutCtgIt> _OutCtgIt _Copy_memmove(_CtgIt _First, _CtgIt _Last, _OutCtgIt _Dest) { auto _FirstPtr ...
If the target type of the pointer is volatile-qualified, it is not possible to use reinterpret_cast to directly cast to const char*. reinterpret_cast is not allowed to cast away const or volatile. const_cast however can do this, while not being able to change the pointer's target type itself. I think a C-style cast wou...
70,736,973
70,737,165
Strange Behavior with pthreads
I have a rather strange problem, despite locking the critical code section in a thread that I am launching, I do not get the right results - #include <stdio.h> #include <pthread.h> #include <thread> #include <mutex> #define NUMTAGS 6 std::mutex foo,bar; pthread_mutex_t mutex; typedef struct PKT{ int ii; int jj; }...
Thanks David, After your comment, I modified my code and it now works - #include <stdio.h> #include <pthread.h> #include <thread> #include <mutex> #define NUMTAGS 6 std::mutex foo,bar; pthread_mutex_t mutex; typedef struct PKT{ int ii; int jj; }pkt; void *print(void *pk) { pthread_mutex_lock(&mutex); ...
70,737,101
70,737,151
Pointer is not incremented (moved) to expected location or pointer arithmetic is not providing expected answer
In the following snippet of code I expect pointer to move to next location i.e. current location + sizeof(datatype) but not happening unless I type cast to int. #include <iostream> #include <string.h> int sizeOf() { int a = 0; int* b = &a; int* c = &a; c++;// expect pointer to move "current location + ...
The difference is in terms of the size of the pointed object. So a difference of 1 means the pointers point to 1 * sizeof(int) bytes apart. For example, &( a[2] ) - &( a[0] ) always gives 2 for a C array. It doesn't matter if it's an array of char, int, or some struct. And it's easy to show why this is necessary, give...
70,737,335
70,737,414
Can anyone explain how to use unique( ) in the vector?
#include<bits/stdc++.h> using namespace std; int main() { vector <int> v = {1, 2 , 3, 2 , 1}; cout << v[0] << " " << v[1] << " " << v[2] << " " << v[3] << " " << v[4] << endl; sort(v.begin(), v.end()); cout << v[0] << " " << v[1] << " " << v[2] << " " << v[3] << " " << v[4] << endl; unique(v.begin(...
Aside the fact, that bits/stdc++.h is not the proper header when taking C++ standard into account (please use iostream, vector and algorithm). From: https://en.cppreference.com/w/cpp/algorithm/unique Eliminates all except the first element from every consecutive group of equivalent elements from the range [first, last...
70,737,355
70,737,455
Is there a better way to modify a char array in a struct? C++
I am trying to read in a cstring from a edit control box in MFC, then put it into a char array in a struct, but since I cannot do something like clientPacket->path = convertfuntion(a); I had to create another char array to store the string then store it element by element. That felt like a bandait solution, is there a ...
I don't see the need to create the intermediate 'holder' char array. I think you can just directly do strcpy(clientPacket->path, a.c_str()); You may want to do this: a= a.substr(0, sizeof(clientPacket->path)-1); before the strcpy to avoid buffer overrun depending on whether the edit text is size limited or not.
70,737,474
70,737,584
Is TMP really faster if the recusion depth is very deep?
I made a simple sqrt struct using TMP. It goes like : template <int N, int i> struct sqrt { static const int val = (i*i <= N && (i + 1)*(i + 1) > N) ? i : sqrt<N, i - 1 >::val; }; but is causes error since it does not have the exit condition, so I added this : template <int N> struct sqrtM<N, 0> { static cons...
The thing is that in TMP you can't go very deep by default. The depth is limited but the limit can be changed (see this). The other thing is that you write your TMP code with recursion but it can be compiled into a non-recursive code so it doesn't have the extra cost of saving the state and doing a function call as it ...
70,737,686
70,737,929
free memory of c++ lambda when execute finished
I'm coding a network function on C++, the HTTP request in background thread, use lambda callback when receive HTTP data. But I don't know how to release the lambda, hopes some help. void foo() { // the `func` must be a heap variable for asynchronously. auto func = new auto ([&](std::string response){ pr...
You can capture lambda inside a lambda: void foo() { std::thread t( [func = [](std::string response) { printf("recv data: %s", response.c_str()); }](){ sleep(2); // simulate a HTTP request. std::string ret = "http result"; func(ret); }); t.detach(); ...
70,738,082
70,738,105
Is there any way to assign default value to a map passed as a parameter by reference to a function in C++?
I'm trying to use map in my recursive functions (as an implementation of DP). Here, I wrote a simple Fibonacci function (I know I can use a normal array here but I want to get some idea which I can use in other functions which will take more complex inputs like pairs, strings, objects etc). #include <bits/stdc++.h> usi...
You can simply overload the function: int fib(int n) { std::map<int, int> map; fib(n, map); } int fib(int n, map<int, int> &memo) { ... } Is this what you meant to achive? Sidenote: You should remove #define int long long, it's not legal C++ and utterly confusing.
70,738,482
70,738,629
How to pass initialization values for the member array in C++ template class arguments?
Let's say I have following template C++ class template<uint32_t FILTER_ORDER, uint32_t BUFFER_LENGTH> class Filter { public: Filter() {} private: float data_buffer[BUFFER_LENGTH]; const float filter_coefficients[FILTER_ORDER + 1]; }; I have been looking for a way how I can pass the coefficients of the fi...
Yes, it is possible in C++20, before that float is not allowed as non-type template parameter. template<uint32_t FILTER_ORDER, uint32_t BUFFER_LENGTH, float...values> class Filter { public: Filter() {} private: float data_buffer[BUFFER_LENGTH]; const float filter_coefficients[FILTER_ORDER + 1]{values...};...
70,738,820
70,739,020
OPENGL C++ tiles rendered with small gaps between them
I have been attempting to recreate my pygame RPG in c++ due to performance problems in pygame. I have started rendering tiles. However when these tiles rendered if you go into full screen, you can see lines between the tiles which I believe to be caused by rounding errors when I calculate the locations of the tiles, or...
Fixed by changing from GL_LINEAR to GL_NEAREST when rendering :) Thank you Raildex
70,738,860
70,741,451
How to store a variable or object on desired memory location?
Let's suppose I have an object of a class as shown below: Myclass obj; Now I want to store this object to my desired memory location. How can I do this? Is it possible or not? I have created an array class which simply insert data of integer type in respective indexes but the size of array is not declared inside the c...
You wrote class newarray { int arr[]; //size not declared This is not allowed. Unfortunately, your compiler did not warn you when compilinhg. You only discovered that this was a problem when your code crashed. You then wonder about "some allocated memory location" and picking one manually. That's not the pro...
70,739,127
70,739,211
How does compiler deduce return type from this lambda expression?
I am creating a web-socket server in C++ with Boost library. My starting point was a Boost example from this site. I have a question with this part of code in the on_run method: ws_.set_option(websocket::stream_base::decorator( [](websocket::response_type& res) { res.set(http::f...
websocket::stream_base::decorator is a template function with one template type parameter. template<class Decorator> decorator( Decorator&& f ); In this call ws_.set_option(websocket::stream_base::decorator( [](websocket::response_type& res) { res.set(http::field::server, st...
70,740,150
70,740,572
Is it possible to provide a constuctor with copy elision for member initialization?
I'm testing different modes for initializing class members with following small code: struct S { S() { std::cout << "ctor\n"; } S(const S&) { std::cout << "cc\n"; } S(S&&) noexcept{ std::cout << "mc\n"; } S& operator=(const S&) { std::cout << "ca\n"; return *this; } S& operator=(S&&) noexcept{ std::...
I wonder if it is possible to provide a constructor which initialize members directly like aggregate initializer. Certainly. Write a constructor that doesn't accept an argument of the member type, but rather accepts arguments that are forwarded to the constructor of the member. In your case, the member type is defaul...
70,740,701
70,740,822
Permutation calculator isn't working in C++
Good day! I am having some trouble with my permutation calculator. For some reason, the end result is always 1. We are not allowed to use recursion at the moment so I opted to use a for loop for finding the factorials. Here is my code: #include <iostream> using namespace std; int fact(int x); int perm(int y, int z); i...
The problem in your code is unecessary abuse of global variables. This function: int fact(int x) { int number, cum = 1; for(number=1;number<=n;number++) cum=cum*number; return cum; } Always calculates the factorial of n. No matter what parameter you pass when calling it, hence here: int perm(int...
70,740,797
70,742,553
How to set cell values using Excel12v C interface
I have an Excel12v function using XLOPER to set some values on an Excel sheet. I can create XLLs fine as per Microsoft's XLL guide. I authored xladd-derive for Rust which enables this an allows returning scalars and ranges of values very simply. However I would like, rather than return a value, to set a random cell to ...
In general, Excel prevents spreadsheet functions from changing the values in cells. In effect, spreadsheet functions are given a read-only view of the values in the sheet. This is the documentation for xlSet which states: xlSet behaves as a Class 3 command-equivalent function; that is, it is available only inside a DL...
70,741,051
70,745,424
Why my natural log function is so imprecise?
Firstly, I'm using this approximation of a natural log. Or look here (4.1.27) for a better representation of formula. Here's my implementation: constexpr double eps = 1e-12; constexpr double my_exp(const double& power) { double numerator = 1; ull denominator = 1; size_t count = 1; double term = numerat...
The line tmp *= mul / tmp_odd; means that each term is also being divided by the denominators of all previous terms, i.e. 1, 1*3, 1*3*5, 1*3*5*7, ... rather than 1, 3, 5, 7, ... as the formula states. The numerator and denominator should therefore be computed independently: double sum = 0; double value = (num - 1) / (n...
70,741,663
70,748,971
How to member pass a function, which has another member function as an argument, to a thread
I have a member function that takes another member function as an argument, which works normally when executed directly on the main thread. However, when trying to run this function in a separate thread, I get the following error on g++: In file included from /usr/include/c++/11/thread:43, from teste.c...
According to @super tip, use std::ref() t = thread(&Shell::function1<Memoria>, this, &Memoria::imprimir, ref(*escalonador->kernel->memoria));
70,742,079
70,742,338
Why can we avoid specifying the type in a lambda capture?
Why is the variable 'n' in 2nd usage of std::generate and within lambda capture not preceded with it's data type in below code? I thought it's important to specify the datatype of all identifiers we use in a c++ code. #include <algorithm> #include <iostream> #include <vector> int f() { static int i; return +...
From cppreference: A capture with an initializer acts as if it declares and explicitly captures a variable declared with type auto, whose declarative region is the body of the lambda expression (that is, it is not in scope within its initializer), [...] Lambdas used the opportunity of a syntax that was anyhow fresh a...
70,743,100
70,751,300
How to check what case is selected with radio button Win 32 api
I am using win 32 api in C++ to devellop a desktop app. At on point I want to use a radio button with two case, and depending on what case is selected by the user I want to create a dialogBox. I use a ressource file to create the dialog box that contains the radio button : IDD_INPUT DIALOG DISCARDABLE 0, 0, 150, 150 S...
You could try to send the BM_GETCHECK message to the control and check the return value. And you will need the HWND of your control, to get that from the control ID, you could try to call GetDlgItem().
70,743,256
70,743,643
String throwing exception
I have the following code with two functions which should throw exceptions when condition is satisfied. Unfortunately the second one with string seems not working and I don't have a clue whats wrong #include "iostream" #include "stdafx.h" #include "string" using namespace std; struct P { int first; string sec...
I do not know what you are trying to experiment, but despite being allowed by the language, throwing objects that are not instances of (subclasses of) std::exception should be avoided. That being said you have a bunch of inconsistencies in your code. First cin >> x.second; will stop at the first blank character. So in ...
70,743,339
70,898,033
Get cwnd of my TCP connection from a program
I am creating a TCP connection from my linux program with boost.asio. I wonder how do I get the value of its congestion window (cwnd) from the program? The only way I know of is to parse /proc/net/tcp, but this does not feel right. I'd rather use a dedicated syscall to get this info. A solution to a similar question (H...
It turned out getsockopt() is able to return the same tcp_info when called with TCP_INFO option: tcp_info tcpi = {}; socklen_t len = sizeof(tcp_info); getsockopt(tcp_socket, SOL_TCP, TCP_INFO, &tcpi, &len); tcpi.tcpi_snd_cwnd; // <-- CWND
70,743,348
70,744,380
How do I fix the assigning numbers to the variable and the number of occurrence?
I managed to formulate a code but I still cannot figure out where I'm getting it wrong, there are two problems the numbers and the number of occurrence. If one is working the other is not. Task: Using while loop, write a program that asks a user to input for a positive number let’s say N. The program then asks the user...
I'm not sure what your code is trying to do. The approach I'd take is simple: keep track of the maximum and the number of occurrences as you read numbers. If you read a number greater than the current maximum, update the current maximum and reset the occurrence counter. If you read a number equal to the current maximu...
70,743,376
70,743,398
Problem with filling a two-dimensional array in c++
I'm trying to fill a two-dimensional array of int in c++. But i have a weird problem. Basically right now i have a code like that : int array[83][86]; int test_1 = 0; int test_2 = 0; for (int x = box.min_corner().x(); x < box.max_corner().x(); x = x + 50) { for (int y = box.min_corner().y(); y < box.max_corner().y(...
You have to reset test_2 to 0 appropriately. Otherwise, you keep incrementing the variable and it eventually goes past the limit of 86.
70,743,728
70,744,216
Can a class with consteval constructor be created on heap in C++?
In the following code struct A has immediate function default constructor, and an object of the struct is created in the dynamic memory be means of new A{}: struct A { consteval A() {} }; int main() { new A{}; } Only Clang accepts it. GCC complains error: the value of '<anonymous>' is not usable in a c...
Which compiler is right here? Invoking a consteval constructor with new is ill-formed. MSVC and GCC are right to reject it; clang is wrong as a diagnostic is required. struct A { consteval A() {} }; consteval makes A::A() an immediate function1. An immediate function can only be called from2,3: another immediate f...
70,743,758
70,745,836
How to interpret the precondition of std::launder?
struct X { int n; }; const X *p = new const X{3}; // #1 new (const_cast<X*>(p)) const X{5}; // #2 const int c = std::launder(p)->n; Assume that the object created at #1 is named obj1 while the object created at #2 is named obj2. The precondition of std::launder is that [ptr.launder] p2 link p represents the addres...
[basic.compound]/3 is not relevant. It specifically says that it applies only for the purpose of pointer arithmetic and comparison. There doesn't actually exist an array for the object. I think when you call std::launder, there are four objects at the relevant address: obj1, obj1.n, obj2 and obj2.n. obj1 and obj1.n are...
70,743,892
70,743,893
How can I set up my class so it can't be inherited from in C++98/C++03?
Using C++98 (or C++03), how can a class (B) be defined, such that no objects can be instantiated from a class (D) deriving from B. struct B {}; struct D : public B {}; D d; // this should result in a compiler error In C++11 (or newer) one could use the final specifier.
I found these possible solutions, each with drawbacks: "named constructors" Define all constructors of the base class private and provide named constructors (static, public method which returns an object of that class). Drawbacks: Using that class is "not-so-clean" / less straightforward. The purpose of the effort sho...
70,744,339
70,757,056
Example of passing a list of strings from Python to C++ function with Cython
I'm going in circles trying to figure out a fairly basic question in Cython. On the Python side, I have a list of variable-length strings. I need to pass these to a C++ function that will process this list and return some calculations (a vector of floats of same length as the input, if that matters). I know how to pass...
Lenormju's first link had the solution. I didn't know you could do memory views into a list, but the solution is much easier than I realized. A very simple minimal example: # cython: language_level=3 # distutils: language = c++ from libcpp.vector cimport vector from libcpp.string cimport string cdef extern from "my_f...
70,744,937
70,745,373
Workaround for passing parameter pack to alias templates (which have non-pack parameters)
Look at this example: template <typename A> struct Foo1 {}; template <typename A, typename B> struct Foo2 {}; struct Bar1 { template <typename A> using Foo = Foo1<A>; }; struct Bar2 { template <typename A, typename B> using Foo = Foo2<A, B>; }; template <typename BAR> struct Something { template...
Workaround is to make the alias variadic: struct Bar1 { template <typename... Ts> using Foo = Foo1<Ts...>; }; struct Bar2 { template <typename... Ts> using Foo = Foo2<Ts...>; }; Demo
70,744,948
70,745,092
Extract from a member pointer the type of class it points to
How make the following compile correctly with C++20, a.k.a calculate extract<mem_fun>::type? Is it possible? Error-scenarios like passing non-member function or private function extract<> are not so important for me. #include <concepts> struct x { void f() { } }; template<auto mem_fun> struct extract { ...
Pointers to members all have type T C::*, where T can be either some type or some function type or even some "abominable" function type. So you just need to specialize on that particular shape: template<auto mem_fun> struct extract; template <typename T, typename C, T C::* v> struct extract<v> { using type = C; };...
70,745,070
70,745,112
LNK2019 Unresolved External Symbol, Can't figure out why?
apologies in advance as this is most likely my own impotence to find the error and simply overlooking the answer. Anyway; when invoking XEngine::MapConstBufferData in my entry point I run into LNK2019, I'm quite clueless as to why but believe the error to lay within the fact that it is template function, all help is hi...
templates require either header-file only implementation, or explicit instantiation. The compiler can't code the template when it sees it in EntryPoint.cpp as it doesn't have the rules. The compiler doesn't realize it needs it when it sees it in XEngine.cpp
70,746,345
70,747,637
Reading custom (.ndev) Json-like file structure
I'm currently creating a custom file structure (File extension is .ndev), to increase my skill in working with files in C++. I can save values to a file in a specific way (See below) { "username": "Nikkie", "password": "test", "role": "Developer", "email": "test@gmail.com" } This doesn't have anything...
From a practical point of view, there is no reason to store your structure in that format. There are simpler ways. Anyhow, here's a starting point (demo): #include <iostream> #include <string> #include <map> #include <iomanip> #include <fstream> using namespace std; // your structure struct person { string name, pa...
70,746,835
70,747,276
How to set a relative path/How to use $(SolutionDir)
I'm trying to make a project compile no matter where it is cloned, but I don't know how to write the relative path in relation to the solution location, for now this is how it looks I tried something with $(SolutionDir) but i don't know how to go one step back from it and into the libraries folder as shown in the curr...
To go one step back from a $(SolutionDir) you can write $(SolutionDir)\..\. You also can go deeper and create a property sheet for your library, so that if you need to use this library in another project, you would need to include only one .prop-file into your .vcxproj. Assuming the library name is cereal and property ...
70,746,893
70,746,902
For multiple instances of the same object, are member variables stored at the same offset?
Say I have a struct Foo: struct Foo { char a; int b; } Foo1, Foo2; The compiler may insert padding so that Foo::a is stored at the start of the object's memory, and Foo::b is stored at an offset of 0x04 (say on a 32-bit system for example). If I create multiple instances of this object Foo1 and Foo2, will they...
For multiple instances of the same object, are member variables stored at the same offset? Yes. If I create multiple instances of this object Foo1 and Foo2, will they always have the same padding? Yes. Is there ever a case where Foo1::b is stored at offset 0x04 and Foo2::b is stored at offset 0x08 for example? No...
70,746,942
70,747,051
Partial specialization of typedef
I want to have a type which is either a typedef or a class. Thus, something like this template< typename T > class A { }; template< typename T > using X< T, true > = T; template< typename T > using X< T, false > = A< T >; Obviously, this does not compile. To overcome this problem I "invented" the following construct, ...
Normally, one would do this: template< typename T, bool E > using X = std::conditional_t<E, T, A<T>>; The only issue here would be if you wanted to use the type X<T, true> in a situation where simply mentioning A<T> would be ill-formed. In that case X<T, true> will be ill-formed even though the result is not A<T> anyw...
70,747,015
70,747,071
Error: Too few Argument in multithreaded code
I have been trying to implement a multithreaded program, I already tried <thread.h> and the code worked perfectly; but now I have to use <pthread.h> library due to some college project. I wrote a long code, but for now the problem i'm struggling with, is about pthread_create function. So, I just write only a part of th...
There are two problems here. First, the function that is the entry point for a thread as specified by the third argument to pthread_create must accept a void * as an argument and return a void *. Your function must conform to that signature. You're free to ignore the parameter and to just return NULL. void *hello(vo...
70,747,306
70,747,417
Optimizing away static variable / passing by reference
In this question Will a static variable always use up memory? it is stated that compilers are allowed to optimize away a static variable if the address is never taken, e.g. like following: void f() { static int i = 3; printf( "%d", i ); } If there exists a function which takes its arguments by reference, is the...
that compilers are allowed to optimize away a static variable if the address is never taken You seem to concentrated on the wrong part of the answer. The answer states: the compiler can do anything it wants to your code so long as the observable behavior is the same The end. You can take the address, don't take it,...
70,747,371
70,780,873
Meson on windows cannot find llvm-lib?
I am trying to port a Linux Library to windows, the library uses meson for compilation. I have a dummy meson.build file: project( 'Dummy', 'cpp', version: '0.0.1', license: 'GPL', default_options : [ 'cpp_std=c++latest', 'default_library=static', 'optimization=3', 'bu...
Those aren't libraries, those are static linkers (also called archivers), which are used to produce static libraries (those ending in .a or .lib, usually). Those are pretty important to meson, and it assumes that it can find the three pieces of the toolchain (The compiler, the archiver, and the [dynamic] linker) for an...
70,747,639
71,875,469
How to get the value of a template class?
I'm trying to get the value of a template class. To get the value of a class, I can easily do like: int get_value() { return *this; } But I want to create a class, and extend it, and don't make get_value() in all classes again. So, I did that: template<typename T> class _extend : public T { public: aut...
Basically: template<class C> class extend : public C { public: using C::C; auto get() { return *this; } }; And a full example: #include <iostream> template<class C> class extend : public C { public: using C::C; auto get() { return...
70,747,645
70,748,343
Trouble understanding Caesar decryption steps
The following code will decrypt a caesar encrypted string given the ciphertext and the key: #include <iostream> std::string decrypt(std::string cipher, int key) { std::string d = ""; for(int i=0; i<cipher.length();i++) { d += ((cipher[i]-65-key+26) %26)+65; } return d; } int main() { std::...
If we reorder the expression slightly, like this: d += (((cipher[i] - 65) + (26 - key)) % 26) + 65; We get a formula for rotating cipher[i] left by key: cipher[i] - 65 brings the ASCII range A..Z into an integer range 0..25 (cipher[i] - 65 + 26 - key) % 26 rotates that value left by key (subtracts key modulo 26) + 65...
70,747,890
70,747,920
Why am I getting this big value at the end?
I need to find the biggest value in an array, but instead I'm getting a huge number at the end. #include <iostream> #include <string> int main() { int masivs[5]; int enter = 0; for (int i = 0; i < 5; i++) { std::cout << "Enter number:"; std::cin >> enter; masivs[i] = enter;...
This is called "off by one" error, because... You are off by one. Usually, this error is caused due to confusion that array indexes start at 0, but in your case you just misjudged the loop counters: if(index > masivs[i + 1]) also: index = masivs[i + 1]; When i is 4, you are trying to access masivs[5] which is past yo...
70,747,951
70,753,029
Access an attribute c++ object from QML
I am having a problem understanding how to use a c++ singleton object from qml. I know that I have to inherit my classes from the QObject class and that I have to expose the properties. And that in order for them to be usable in the qml I have to do setContextProperty("ClassName", &class name). However, if we admit tha...
You could do any of the following: Add a public slot in API class: API.cpp: QString API::getUserName() { return user.getName(); } main.qml: Component.onCompleted: console.log( API.getUserName() ) Make User a Q_PROPERTY in API class: API.h: Q_PROPERTY( User* user READ user NOTIFY userChanged) main.qml: Component....
70,747,983
70,749,396
Adding QWidget into QGridLayout adds border to layout?
Currently I have my program organized this way in QTDesigner (which I use with VS 2022): QMainWindow->centralWidget(QWidget)->QTabWidget->Tab(QWidget)->QGridLayout. All these elements are created in QtDesigner. In my cpp code I'm downloading some data and generating QTableWidget* m_table. Unfortunately after adding it ...
Look into Qt's stylesheets. You should be able to style your QTableWidget in any way you want to. Keep in mind a QTableWidget is specialized version of QTableView, so you have set your stylesheet to a QTableView: m_table->setStyleSheet("QTableView {background: transparent; border: 1px solid green;}"); Here are some li...
70,748,378
70,749,137
How to insert a type between all elements of a parameter pack?
I have: struct spacer : foo<bar>{}; struct sequence : baz<qux, spacer, quz, spacer, plugh>{}; I would like to be able to write (something like this, exact syntax doesn't matter): struct spaced_sequence : SPACED_BAZ<qux, quz, plugh>{}; Can this be done with macros/templates/anything else?
You can do the following: Create a base case function template that appends a single type T to some specialization of baz template<typename T, typename ... Args> auto append(baz<Args...>) -> baz<Args..., T>; Note that no spacer is added here, since T is the last type we're adding. Then write a recursive case, also as ...
70,748,442
70,752,711
Passing 'this' pointer to a static method in a parent class
I am writing an embedded application using freeRTOS and I'm trying to do it in a neat, object-oriented fashion. To start a FreeRTOS task from within an object, you need to give it a static function. In order to make it possible to use non-static variables inside that function, I've been implementing it in the following...
Declaring a virtual loop function in BaseMode worked. Forgot these even existed.
70,748,458
70,748,694
How to make function for save and replay tones on Arduino buzzer?
i have a question about my project in Arduino, i have this array of frequencies for notes: int note[] = {261, 293, 329, 349, 392, 440, 494, 523}; and this function for play notes if one of pushbuttons is pressed: void play(float U_ADC0){ if(U_ADC0 >= 4.80) { // ADC conversion (Voltage value) PB1 ...
I would use one button (let's call it the record button) to switch between play & record and only play. In this way, whenever you push buttons that get those buzzer frequencies will not save, but when you like the melody and want to save you can click the record button and start to save. For making this happen, follow ...
70,748,602
70,764,194
How can I get CPU idle residency in macOS on arm64 and x86
I'm trying to get the idle residency of the CPU in macOS (C-State C0 residency on x86 unsure on arm64). I am aware you can find this info by running something like sudo powermetrics -i1 -n1 -s cpu_power | grep residency in the terminal, but I need a way to pull this info using C, C++, Objective-C, or even Assembly...e...
The powermetrics tool use private API to do this: IOReportStateGetResidency You could try to import it and with some reversing use yourself too: https://github.com/samdmarshall/OSXPrivateSDK/blob/master/PrivateSDK10.10.sparse.sdk/usr/local/include/IOReport.h https://opensource.apple.com/source/PowerManagement/PowerMana...
70,749,182
70,756,348
meson cannot find a conan package, despite setting pkg_config path?
I am trying to build on windows using meson and conan. I installed packages for VS 2017 using conan and generated the PC files in the build directory. Inside my conan.py I have the snippet: meson = Meson(self) self.output.warn(self.folders.generators) meson.configure(build_folder="build", args=[ ...
Try specify instead -Dbuild.pkg_config_path=... from this Since 0.51.0, some options are specified per machine rather than globally for all machine configurations. Prefixing the option with build. just affects the build machine configuration... build.pkg_config_path controls the paths pkg-config will search for just n...
70,749,292
70,749,480
C# to C++: Convert C# Time calculation to C++ chrono
I've got the task to convert some C# code to C++ and I've problems with chrono. Goal is to round a time to a variable time span. C#: int iRoundTo = 30; // can be 45 or other variable value, not a const DateTime dt = Floor(DateTime.Now, new TimeSpan(0, 0, 0, iRoundTo)); I found a solution with const iRoundTo but this i...
I'm doing a bit of guessing with this answer, but my guess is that you want to truncate the current time to the floor of the current half minute (in case of iRoundTo == 30). If I'm correct, this is easy to do as long as iRoundTo is a compile-time constant. #include <chrono> #include <iostream> int main() { using R...
70,750,236
70,750,403
How can I solve the error -- error: invalid types ‘int[int]’ for array subscript?
#include <iostream> #include <iomanip> using namespace std; int col=10; int row=0; void avg(int * ar,int row, int col) { float size= row * col; int sum=0, ave; for(int i=0; i<row; i++) { for(int j=0; j<col; j++){ sum+=ar[i][j]; cout<<sum;} } ave=sum/siz...
Your function parameter ar is a int*. But when you wrote sum+=ar[i][j] you're subscripting it as if we had a 2D array. You can only subscript it for one dimension like arr[i]. Additionally, row and col are not constant expressions. And in Standard C++ the size of an array must be a compile time constant(constant expres...
70,750,288
70,750,343
can derived class access base class non-static members without object of the base class
can derived class access base class non-static members without object of the base class class base { public: int data; void f1() { } }; class derived : base { public : void f() { base::data = 44; // is this possible cout << base::data << endl; } }; why does the below ...
In your 1st example class derived : base { void f() { base::data = 44; } }; f() is not-static. It works on an object of derived, which includes an object of base. So, base::data = 44; is equivalent to data = 44; and it accesses the member of the object. In the 2nd example class derived : base { ...
70,751,049
70,751,757
question on initializeOpenGLFunctions returning false
I'm running into the following segfault after initializeGL() fails. Any ideas as to what might cause this? There is no problem when I inherit from QOpenGLFunctions but I need v3.0 functionality. class MyGLWidget : public QOpenGLWidget, protected QOpenGLFunctions QOpenGLFunctions_3_3_Compatibility::glClearColor (this=0...
I solved this problem as follows. I inherited from QOpenGLFunctions and then used the corresponding Core profile 3.3 in my case when needed. class MyGLWidget : public QOpenGLWidget, protected QOpenGLFunctions { Q_OBJECT ... protected: void initializeGL() override { initializeOpenGLFunctions(); aut...
70,751,060
70,751,135
do for loops deallocate memory after they finish
Let's say you wrote a for loop: for (int i = 0; i < 10; i++) for (int j = 0; j < 10; j++) Is that for loop creating 10 different j variables, and does it deallocate i and j after its done looping? I have seen many people do this instead: int i, j, k for (i = 0; i < 10; i++) for (j = 0; j < 10; j++) //..All The ...
All of the variables in question are being created in automatic storage. They are destroyed when they go out of scope. The two examples are simply declaring the variables in different scopes. In the first example, i is scoped to the outer loop, meaning i exists only while the loop is running. It is created when the loo...
70,751,387
70,751,684
Returning multiple unique_ptr from factory mock
How can I return multiple object from a mocked factory returning unique_ptr, when the calls cannot be identified through different input parameters to the called function? I'm doing this: EXPECT_CALL(MyFactoryMock, create()) .WillRepeatedly(Return(ByMove(std::make_unique<MyObjectTypeMock>()))); And run-time error is...
ByMove is designed to move a predefined value that you prepared in your test, so it can only be called once. If you need something else, you'll need to write it yourself explicitly. Here's an excerpt from the googletest documentation: Quiz time! What do you think will happen if a Return(ByMove(...)) action is performe...
70,751,584
70,751,666
Extremely long linking time on windows but not Linux
I have a program that on Linux compiles and links in about 15 minutes from scratch, and then takes about 1 minute to compile on subsequent rebuilds. The exact same program is taking hours to link on windows. The compilation step is the same, but it just gets hanged on the linking step for a really long time. Is there a...
I don't think it's possible to profile but you can normally significantly speed up link via /incremental and /debug:fastlink flags.
70,752,045
70,752,443
How can I return `map<K, V>::iterator`? (`map` class extends `std::map`)
I making a custom map class (kc::map) that extends std::map, and I want to add at_index(), and I need to return map<K, V>::iterator. But when I return map<K, V>, this error occurs: error: invalid use of incomplete type ‘class kc::map<K, V>’: namespace kc { template<typename K, typename V> class map : public std::ma...
Ignoring the real problems with the code (deriving from standard containers is not recommended and at_index returns a dangling iterator to the local object m) to get the code to compile you have two options. within a class you don't need to prefix members of the class with the class name. As iterator isn't a class mem...
70,752,203
70,752,347
std::move versus copy elision
The following code compiles without warnings in Visual Studio 2019 msvc x64: class ThreadRunner { public: void start() { m_thread = std::move(std::thread(&ThreadRunner::runInThread, this)); } private: void runInThread() { for (int i = 0; i < 1000 * 1000; i++) { std::cout << ...
The two versions m_thread = std::thread(&ThreadRunner::runInThread, this); and m_thread = std::move(std::thread(&ThreadRunner::runInThread, this)); behave identically. No elision is possible in either case, since this is assignment to, not initialization of, m_thread. The temporary object must be constructed and then...
70,752,236
70,752,275
Can a class member function be invoked without an object?
I was learning the history about Lambda's in C++ and saw the following code (which is not lambda) but I am surprised how it Works struct Printer{ void operator() (int x) const{ std::cout << x << '\n'; } }; int main(){ std::vector <int> vint; //doing it the C++ 03 way vint.push_back(1); vint.push_ba...
Printer() is an instance of the Printer class. It will result in a temporary object of type Printer which is passed to std::for_each. This is the object on which operator() is called by std::for_each internally. Without an object of type Printer, it is not possible to call the operator() member function.
70,752,718
70,752,861
convert const std::shared_ptr<const T> into boost::shared_ptr<T>
I need convert a variable type of const std::shared_ptr<const T> into boost::shared_ptr<T>. In the following scanCallback(), I can not modify the param const std::shared_ptr<const io_adaptor::msg::PandarScan> msg. The msg is very big in memory, which contains large lidar points. PushScanPacket() func's arg is boost::s...
You cannot transfer ownership from std::shared_ptr to boost::shared_ptr. You might from a std::unique_ptr though. But you can create a boost::shared_ptr with a custom deleter. boost::shared_ptr<io_adaptor::msg::PandarScan> msg_boost(const_cast<io_adaptor::msg::PandarScan*>(msg.get()), [msg = msg](auto...
70,752,912
70,752,993
Understanding const reference in assignment when constructing object
Today I see this piece of code and I'm wondering to know what it is exactly doing this const reference in an assignment where a new object is created. (I don't know how to name this kind of assignments.) std::string const& p = s.c_str(); // s is a std::string I understand that something like std::string const& p = s; ...
From std::string::c_str's documentation, it returns: a pointer to an array that contains a null-terminated sequence of characters (i.e., a C-string) representing the current value of the string object. That is, a const char*. So when you wrote: std::string const& p = s.c_str(); In the above statement, the const char...
70,753,018
70,755,061
Why does all elements get replaced when inserting new elements in boost multi_index container?
When I insert in the main function one after the other elements are inserted properly but when I try to do that through a function all values get replaced by the last elements. Please refer the following code : struct X { std::string panelid; // assume unique std::string messageid; // assume unique std::str...
You didn't supply working code. You're overusing pointers. The first error makes it so the code can compile: int Insert(X newframe, Container *Cont) should be int Insert(X newframe, Container& c) The real problem is that you're storing pointers, not frames. The pointer inserted in the Insert function are dangling (th...
70,753,041
70,753,437
Why does this construction of std::function from lambda not compile?
Why doesnt the following line compile? std::function<void (int)> f = [](int&){}; But many other alternatives do: [[maybe_unused]] std::function<void (const int&)> f1 = [](const int&){}; //[[maybe_unused]] // doesnt compile because losing constness //std::function<void (const int&)> f2 = [](int&){};...
std::function forwards it's arguments to it's target. The lambda assigned to f14 can't be called with an rvalue. You are also incorrect about f10, that is the same case as f14. Top level const is ignored in arguments. Each of f11, f12, f15 and f16 are the same case.
70,753,213
70,753,468
Is it good practice to declare derivate classes in the same C++ header?
I'm declaring a pure virtual class that will provide a unified interface for a handful of derived classes. My instinctual way to organize this would be to create a base folder with the header for the base class (e.g lib/Base.h) and then create subfolders for the header + source file of the derived classes (so lib/impl...
Two-file folders (like lib/implA/ImplA.h, lib/implA/ImplA.cpp) are unnecessary, for small projects people usually just put everything in lib/. If lib/ becomes too cluttered, put this whole hierarchy in lib/my_hierarchy/Base.h, lib/my_hierarchy/ImplA.cpp, etc. Maybe extract a logical subsystem instead of a hierarchy. Ju...
70,753,294
70,753,348
What is this 'bad:' label generated by Cython?
While cythonizing my Cython source code files, I can see a dozen of warnings about a label named 'bad:' generated by Cython, for example: read_input.cpp:30037:3: warning: label ‘bad’ defined but not used [-Wunused-label] The C++ generated function is like this: static PyObject* __pyx_convert__to_py_struct__VehicleCaps...
It's for goto bad if something fails in the function, but it doesn't look like anything can fail, so it's unused. It isn't a problem so you can ignore it. But Cython generally tries not to generate unused labels, so feel free to report it as a (small) bug
70,753,352
70,753,949
Cannot get operator() pointer of std::bind() returned object
I need to extract the type of a function object parameter. Lambdas get translated into a closure object with the operator(). std::function has got the operator(), too. So, I can get a pointer to the operator() to pass to another function, in this way: template <typename F, typename T, typename R, typename ... Args> voi...
What you want to do is unfortunately impossible because the return type of std::bind is too loosely specified by the standard. std::function::operator() is clearly defined by the standard, so you can match it against R (T::*)(Args... ), see [func.wrap.func.general], for lambda functions, it's not that clear from [expr...
70,754,244
70,757,310
How to write parallelly into a container
I'm working with C++14 and I don't know how to write parallelly into a container with multi-threading. Let's say I have such a map: std::map<int, int> mp {{1, 0}, {2, 0}, {3, 0}} and a function as below: void updateValue(int& value) { value = xxx; // heavy calculation } Then I try to create three threads: std::vec...
Your example is safe as-is, and doesn't require any additional synchronization. [container.requirements.dataraces]/2 Notwithstanding [res.on.data.races], implementations are required to avoid data races when the contents of the contained object in different elements in the same container, excepting vector<bool>, are m...
70,754,848
70,754,897
How to fix the Segmentation fault (core dumped) in C++?
I'm writing a program that combines 2 vectors and sorts them and then prints the vector but I'm not using a third vector. Instead I'm combining one vector with another and then sorting the combined vector. But I get a error called "Segmentation fault". here's the code: #include<bits/stdc++.h> using namespace std; int ...
Here: vector<int> nums1, nums2; for(int i=0; i<m; i++) cin >> nums1[i]; // this causes undefined behavior for(int i=0; i<n; i++) cin >> nums2[i]; // also this one your vectors have no buffer to store data so you need to do this before using operator[]: vector<int> nums1(m), nums2(n); nums1.push_back(2); // will add ...
70,755,447
70,768,788
Close connection with client after inactivty period
I'm currently managing a server that can serve at most MAX_CLIENTS clients concurrently. This is the code I've written so far: //create and bind listen_socket_ struct pollfd poll_fds_[MAX_CLIENTS]; for (auto& poll_fd: poll_fds_) { poll_fd.fd = -1; } listen(listen_socket_, MAX_CLIENTS); poll_fds_[0].fd = listen_...
You could close the client connection when the client has not sent any data for a specific time. For each client, you need to store the time when the last data was received. Periodically, for example when poll() returns because the timeout expired, you need to check this time for all clients. When this time to too long...
70,755,471
70,756,174
Is there a backend optimizer in LLVM?
I can get the optimization level from the command llc -help -O=<char> - Optimization level. [-O0, -O1, -O2, or -O3] (default = '-O2') I want to know what the optimization does exactly. So, I'm searching the source code of the backend optimizer. I google it by "llvm backend optimizer", but there is no inf...
Apparently there are backend optimizers options in llvm. They are however not well documented [1,2]. The TargetMachine [3] class has functions getOptLevel and setOptLevel to set an optimization level from 0-3 for a specific target machine, so starting from there you can try to track where it is used. [1] https://llvm.o...
70,755,499
70,759,851
Create std::chrono::zoned_time from zone and time
I have a datetime in a platonic sense, i.e some date and time (like 18th of January 2022 15:15:00) and I know in which timezone it represent something, e.g "Europe/Moscow" I want to create std::chrono::zoned_time. Is is possible? I looked at the constructors and it seems all of them require either sys_time or local_tim...
#include <chrono> #include <iostream> int main() { using namespace std::literals; std::chrono::zoned_time zt{"Europe/Moscow", std::chrono::local_days{18d/std::chrono::January/2022} + 15h + 15min}; std::cout << zt << '\n'; } local_time isn't necessarily the computer's local time. It is a local tim...
70,755,669
70,755,774
The template function encountered an error when passed in a numeric literal, but string literals didn't
I'm writing this code #include <iostream> #include <string> template <typename T> void Print(T& value) { std::cout << value << std::endl; } int main() { Print("Hello"); Print(1); } And when compiling, compilers told an error that “void Print<int>(T &)' : cannot convert argument 1 from 'int' to 'T &'". B...
Case 1 Here we consider how Print(1); works. In this case, the problem is that 1 is an rvalue and you're trying to bind that rvalue to a lvalue reference to nonconst T( that is, T&) which is not possible and hence the error. For example you cannot have: void Print(int &value) { std::cout << value << std::endl; } i...
70,755,720
70,757,636
How can I minimize boilerplate code associated with std::thread?
I have several classes like this in my C++ code: class ThreadRunner { public: void start() { m_thread = std::thread(&ThreadRunner::runInThread, this); } void stop() { m_terminate = true; } ~ThreadRunner() { m_terminate = true; if (m_thread.joinable()) { m_...
Your std::jthread code can be simplified to: class ThreadRunner { public: void start() { m_thread = std::jthread(&ThreadRunner::runInThread, this); } void stop() { m_thread.request_stop(); } private: void runInThread() { size_t i = 0; auto stopToken = m_thread.get_sto...