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,536,136
73,536,232
struct with variable length array in std::variant
So I'm working with this struct type with variable length array member, like this: struct Entry; struct Data { int members; size_t entries_size; Entry entries[1]; }; The entries_size member is the actual size of the entires array, it is only known when read from network. The problem is that I'd like to us...
As has been pointed out, this is not legal C++. It just wont work this way. However, if the amount of entries is bound, it might be possible to do this: template <std::size_t N> struct Data { int members; static constexpr std::size_t entries_size = N; Entry entries[N]; }; // Of couse, you might want to use ...
73,536,861
73,567,816
How to handle multiple inheritance of same methods or diamond problem with CRTP static polymorphism?
I want to implement polymorphism statically with CRTP. I want to create several base classes that provide functionalities. However the functionalities can be overlapping. However if they overlap, they are identical. Suppose I have template<class derived> class Boxer { public: void walk(int nsteps) { for (a...
I found the answer to my question. I do not take credit for the solution. One possible solution can be found at the following webpage https://www.fluentcpp.com/2018/08/28/removing-duplicates-crtp-base-classes/ of Jonathan Boccara's blog. Another solution is provided in Matthew Borkowski's comment within the same page, ...
73,537,185
73,537,222
Left View Of a Binary Tree
To find set of all nodes that are visible from left side of binary tree. vector<int> getLeftView(TreeNode<int> *root) { static vector<int> res; // Your code here if(root){ res.push_back(root->data); if(root->left) getLeftView(root->left); el...
You used static because you need a single instance of the vector to be used across the recursion. But static is not the way; it causes there to be just one instance of the vector in the entire program as such. There are various solutions, one of which is to split the function into the API and recursive part: void getLe...
73,537,755
73,543,913
What's the point of `viewable_range` concept?
[range.refinements] The viewable_­range concept specifies the requirements of a range type that can be converted to a view safely. It's mandatory implementation roughly states that a range further satisfies viewable_range if either it's simply a view, e.g. std::string_view, or it's an lvalue reference (even when its...
What idea does this concept capture? Specifically, how could its instance "be converted to a view safely" and why do I want such conversion? What does "safety" even mean here? Any range can be converted to a view, simply by doing this: template <input_range R> auto into_view(R&& r) { return ref_view(r); } But th...
73,537,920
73,547,405
LLVM opt unable to print instructions from a specific function, But it does for the rest of the functions in the IR
I am new to llvm framework and was able to run a basic pass to iterate over instructions in a simple IR function with only entry basic block, but to expand upon that I got an .ll file from clang for a simple c function ( don't mind the correctness of the function I don't care about it for the sake of learning llvm at l...
See the optnone in: ; Function Attrs: noinline nounwind optnone uwtable define dso_local i32 @fact(i32 noundef %n) #0 { That means that this function is opting out of optimizations, hence your pass will not be run on that function. You can manually remove the optnone from the definition of #0 at the bottom (note: th...
73,538,141
73,538,641
How to assign a specific number to all elements of matrix in vector<vector<int>> matrix_name without using for loop stuff?
like we do this in array thing to assign a specific num to all elements of array- vector<int> arr(n,-1); So ya,above i mention how to do it in array but what about vector<vector> matrix_name?
Just as you can initialize a vector with a number of integers, given a default integer value, you can also initialize a vector with a number of other vectors, given a default value for that other vector. That way you can easily create a multidimensional vector. Example: int nr_of_rows = 30; int nr_of_columns = 40; std:...
73,538,190
73,538,359
C++ Sized template deduction
I want to create a wrapper around with std::array with some extended functionality. The class should be instantiable via an std::initializer_list. I also need a constructor to which I can pass an existing instance of the class plus a "suffix", meaning that the instance need to be of size + 1. #include <stddef.h> #inclu...
with C++20 you can achieve this by adding 2 user defined deduction guides: template<typename... Ts> JsonPointer(Ts... ts)->JsonPointer<sizeof...(Ts)>; template<size_t S> JsonPointer(JsonPointer<S> existing, const char* suffix)->JsonPointer<S + 1>; they allow the compiler to find the correct deduction without naming t...
73,538,780
73,538,982
Program cannot be executed because Cygcurl-4.dll was not found
What I did: I downloaded the code and applications from a c++ course for projects that I was doing online. I am using windows 10, everything like mingw, cygwin etc. are installed and path is also setted up in the system Cygwin is installed and setted up with default packages. Issue: When I try to run the .exe applica...
The lib is here https://cygwin.com/packages/summary/libcurl4.html libcurl4 shared object is usr/bin/cygcurl-4.dll for Windows (you can see in package files) Be careful to install the x86_64 version if your system is 64 bits.
73,538,806
73,539,679
Visual Studio exhibits inconsistent behavior in Create a new C++ project
I'm using Visual Studio Community 2022 (64-bit), Version 17.1.6 according to VS Help->About but 17.3.2 according to VS Installer, on Windows 10. I've been programming in C# for some time and decided to try C++. I downloaded the workload Desktop development with C++ through VS Installer->Modify. But I cannot see the C++...
I have found the reason for this behavior. I start VS using an icon (shortcut) pinned to start in Windows 10. This icon was pointing at an old version of VS. When VS was updated and a new workload was added, this icon still pointed to the old VS version.  I removed this icon and created a new one, and everything works ...
73,539,348
73,539,390
How to make a vectors unmodifiable when passing?
My wording might not be correct, but I hope you'll understand what I mean. Basically I have a map<enum class, vector<struct*>>. I want to pass the whole map without the vectors' contents being modifiable. I need the structs as pointers, because I save references to some of them e.g. to the player instance and they'll g...
First of all, you should declare the member function itself const, otherwise it can't pick the member function for the const circumstance when the object itself is const. Second, you don't have to think about the exact typing, you can let the compiler figure it out by saying const auto&. then it will return a constant ...
73,539,727
73,540,306
Valgrind relative paths in suppression file
Valgrind can generate suppression file, but it contains absolute paths to libraries by default. But I want to share this suppression file between multiple computers, my project may be stored on different paths. How can I specify relative paths to libraries in .supp file?
The documentation says: Locations may be names of either shared objects, functions, or source lines. They begin with obj:, fun:, or src: respectively. Function, object, and file names to match against may use the wildcard characters * and ?. Source lines are specified using the form filename[:lineNumber]. Therefore, ...
73,540,342
74,411,216
Why does std::initializer_list lack cbegin/cend/empty etc. methods?
I wonder why std::initializer_list has begin/end methods, but lacks cbegin/cend/empty, etc. methods. Minimizing std::initializer_list is one possibility, however, what is the point of minimizing it? I think such methods do not just belong to the containers, they are also useful for std::initializer_list. Why?
Probably to minimize std::initializer_list, otherwise it would be duplicated with std::array.
73,541,305
73,560,332
Can't operate on vectors in C++ (Vscode)
I'm using the g++ compiler and used the https://code.visualstudio.com/docs/languages/cpp guide to install everything. Never had any sort of problem. I can initialise a vector from the standard library, but as soon as I attempt to initialise it with values, or add to it, or print its size after adding to it, I get a bla...
Thanks to @n. 1.8e9-where's-my-share m. I was able to find an answer. The problem was to do with Vscode not being able to display the vector. I ran the compiled .exe using the mingw64 console (outside of vsc, not the internal one) and it produced the correct output.
73,542,624
73,545,448
Define a lambda creation
How can I make a general lambda creator, e.g, something like this: #define LAMBDA(f, args...) to create lambda: [&](){ return f(args...); }; So I can do: int main { int a, b, c, d; auto lambda4 = LAMBDA(foo4, a, b , c, d); int e, f; auto lambda2 = LAMBDA(foo2, e, f); } I'm restricted to using C++14.
Please do not use macros for this. It just obfuscates the code. The best solution is std::bind_front: auto l4 = std::bind_front(foo4, a, b, c, d); But that's C++20. With C++14 you can use std::bind. However you state you cannot use it. We are then left with implementing a bind full function. Getting one off the ground...
73,542,960
73,545,651
How To Properly Call a Method From a Mocked Method in Google Test/Mock
In Gmock, I'm trying to get a mocked method to sleep for a few milliseconds and then call a method in the Class under Test. Here is an example of what I'm trying to do: EXPECT_CALL(mockedClass, mockedMethod()) .Times(1) .WillOnce(DoAll(Wait(100), ClassUnderTest.MethodToCall())); I've defined Wait() a l...
Try using InvokeWithoutArgs, smth like this: EXPECT_CALL(mockedClass, mockedMethod()) .WillOnce(DoAll(Wait(100), InvokeWithoutArgs([&ClassUnderTest]() { ClassUnderTest.MethodToCall(); } )); Times(1) is not needed with WillOnce.
73,543,069
73,545,728
Scons set s directory as NoClean
I'm using scons as my build system of c++. There's a sub directory that contains a static library. I've tried to set: NoClean("${PATH_TO_DIR}") But the files in this directory are still removed by scons -c. Is there a way to prevent this command from removing all files generated in this directory?
The flag -c works more or less like this: List all the files that could be built by this call of scons if the flag was not there. Add to the list relevant files marked to be cleaned with Clean(). Delete from the list the files marked with NoClean() (non-recursively). Remove all the files that are remaining on the list...
73,543,875
73,546,736
Absolute hysteresis calculation in C++
I want to implement a template function, which detects if the difference of ValueA and ValueB is bigger than a given hystersis. e.x. ValueA=5, ValueB=7, Hystersis=1 -> true ValueA=5, ValueB=7, Hystersis=3 -> false ValueA=-5, ValueB=1, Hystersis=7 -> false So I implemented this function: template<typename T> bool MyCl...
I have the following solution for integers: template<typename T> bool IsHysteresisExceeded(T ValueA, T ValueB, T Hysteresis) { T ValueMax = std::max(ValueA, ValueB); T ValueMin = std::min(ValueA, ValueB); assert(Hysteresis >= 0); T underflowRange = std::numeric_limits<T>::min() + Hysteresis; bool un...
73,544,311
73,544,579
What mechanism ensures that std::shared_ptr control block is thread-safe?
From articles like std::shared_ptr thread safety, I know that the control block of a std::shared_ptr is guaranteed to be thread-safe by the standard whilst the actual data pointed to is not inherently thread-safe (i.e., it is up to me as the user to make it so). What I haven't been able to find in my research is an ans...
There isn't really much machinery required for this. For a rough sketch (not including all the requirements/features of the standard std::shared_ptr): You only need to make sure that the reference counter is atomic, that it is incremented/decremented atomically and accessed with acquire/release semantics (actually some...
73,544,740
73,544,885
How to pass std::thread as thread id in PostThreadMessage?
How could I pass the id of a std::thread thread as the id into PostThreadMessage? Like suppose, I have a thread: // Worker Thread auto thread_func = [](){ while(true) { MSG msg; if(GetMessage(&msg, NULL, 0, 0)) { // Do appropriate stuff depending on the message } } }; std::...
You can get the underlying, "Windows-style" thread handle for a std::thread object by calling its native_handle() member function. From that, you can retrieve the thread's ID by calling the GetThreadId WinAPI function, and passing that native handle as its argument. Here's a short code snippet that may be what you'd wa...
73,544,840
73,545,430
In C++, if a funcion takes in a const std::string& as input, can I always call with std::move() on the string input?
I don't know much about the function, except it takes a const std::string&, and I want to call this function from inside a class, and the string input I'm sending in is returned from an instance function on this class. Is std::move() usage here always safe and more performant, given what we know? //In some header file:...
std::move actually does absolutely nothing here: some_func_I_only_know_its_signature(std::move(getMyString())); The return value of getMyString is already an rvlaue. The thing is std::move actually doesn't move anything. This is a common misconception. All it does is cast an lvalue to an rvalue. If the value is an rva...
73,545,297
73,546,158
Is there any way to construct an std::initializer_list from an unknown number of arguments?
Hi there so im having some trouble battling a silly API. We have a function that is something along the lines of void foo(std::initializer_list<T> access_list); And what I want to do is take a run-time JSON array and use it to call this function. for example suppose the JSON was data : [ { x : 10, y : 20 }...
If you are stuck with void foo(std::initializer_list<T> access_list); and you've populated a vector<T> with the data you'd like to supply to foo<T>, then you could build a runtime translator. Caveats: The max number of elements you aim to support must be known at compile time. It's terribly slow to compile. It instant...
73,545,353
73,546,965
openssl Could Not Find libcrypto-3-x64.dll
I connected openssl to my project and it compiles and runs well, but next to the program after compiling there is a file libcrypto-3-x64.dll, without which the program will not run, so the question is how do I use openssl without this dll how to integrate it into the project? I found out what the problem is, with the d...
I solved my problem and leave the answer here, just add 2 libraries in Linker => Additional Dependencies Ws2_32.lib Crypt32.lib
73,546,146
73,546,739
how to call a function through a variable number of parameters
How to make a function call with a variable number of parameters? to make it look something like this: if (f(args...)) Example to reproduce: template <class callable, class... arguments> void timer(callable&& f, arguments&&... args ) { f(args...); } class Client { public: void receive(int, int) { ...
You can use std::invoke(f, args...); instead of f(args...).¹ I've rarely used pointers to member functions, to be honest, but on cppreference I see that for a pointer to a unary member function f of a class C, being c such an object of class C, the call syntax would be (c.*p)(x), being x the argument other than this/c...
73,546,220
73,547,309
What does buffer overrun error in uint32_t mean?
I'm trying to write ARGB color data into a uint32_t variable through a for loop. I get an error: invalid write to m_imagedata[i][1],wriable range is 0 to 0 if (!render){ uint32_t* m_imagedata = nullptr; } else{ m_imagedata = new uint32_t(m_viewportheight * m_viewportwidth); } for (uint32_t i = 0; i <...
You have the syntax for dynamically allocating an array wrong. It should be m_imagedata = new uint32_t[m_viewportheight * m_viewportwidth]; and then you'd have to delete it using the delete[] form of delete i.e. delete[] m_imagedata; However, as others have noted in comments if what you want is an array that can be d...
73,547,958
73,548,957
Binding const rvalues reference to non-const rvalues?
The following quotes are needed in the question: [dcl.init.ref]/5: 5- A reference to type “cv1 T1” is initialized by an expression of type “cv2 T2” as follows: (5.1) [..] (5.2) [..] (5.3) Otherwise, if the initializer expression (5.3.1) is an rvalue (but not a bit-field) or function lvalue and “cv1 T1” is reference-...
Here's my first question. The reference r1 is reference to const int and the resulting glvalue is an xvalue denoting an object of type int. So how r1, which is of type const int&&, is now binding to an xvalue of type int? Is this valid binding? Yes, that's what happens. I fail to see the issue here. I know that [con...
73,548,215
73,548,361
Handling multiple data representation for modifying data in vectors in C++
I have the simple data structure describing 2d point in cartesian coordinate system, like below. struct CartPoint { double x; double y; } and second strucutre, representing 2d point in polar coordinate system struct PolarPoint { double r; double alpha; } and also two functions allowing me to translate...
It's likely the most idiomatic to create an intermediary class that can be viewed as either CartPoint or PolarPoint. You can do this multiple ways: containment and getters, or inheritance. Then you can store a vector of these points. CartPoint toCartPoint(const PolarPoint& pp) { ... } CartPoint toPolarPoint(const CartP...
73,549,126
73,549,288
Why does heterogenous version of erase for associative containers take in forwarding reference?
Is there any particular reason why heterogeneous version of erase in associative containers (std::map, std::unordered_map, std::multimap and std::unordered_multimap) takes in a forwarding reference and all other heterogeneous functions (find/equal_range, count, contains) take in const-reference? For instance in case o...
After doing a bit more research I've found the original proposal p2077 which explains it (paragraphs 2 and 3.1). If the overload template <class K> size_type erase( const K& x ); existed, it would be chosen when passing an object of a type, which is implicitly convertible to either iterator or const_iterator and that ...
73,549,440
73,550,183
Is there a faster way to calculate the inverse of a given nxn matrix?
I'm working on a program that requires calculating the inverse of an 8x8 matrix as fast as possible. Here's the code I wrote: class matrix { public: int w, h; std::vector<std::vector<float>> cell; matrix(int width, int height) { w = width; h = height; cell.resize(width); ...
Your implementation have problems as others commented on the question. The largest bottleneck is the algorithm itself, calculating tons of determinants.(It's O(n!)!) If you want a simple implementation, just implement Gaussian elimination. See finding the inverse of a matrix and the pseudo code at Wikipedia. It'll perf...
73,550,037
73,550,155
Finding max value in a array
I'm doing a program that finds the max value in a array. I done it but I found a strange bug. #include<iostream> using namespace std; int main() { int n; //input number of elements in cin >> n; int arr[n]; for (int i = 0; i < n; i++) { cin >> arr[i]; //input array's elements } int max_val...
In Arrays the first index starts with 0 and ends in n - 1 assuming the array is of length n so when looping from i = 1 to i <= n. n is now larger than n - 1. the solution would be to start from 0 and end at i < n hence: #include<iostream> using namespace std; int main() { int n; //input number of elements in ...
73,550,141
73,560,318
Unexplained profiling data from llvm when compiling simple C++ program
When profiling the following main.cpp file, I am getting "0" for the "test1 complete" line indicating the line has not been executed when I expect to get "1" main.cpp #include <cassert> #include <iostream> using namespace std; void test1() { cout << "test1 start" << endl; string pdx; assert(pdx == ""); cout <...
This is a bug, and should be reported to the people who make clang.
73,550,146
73,556,379
Why can't constexpr be used for non-const variables when the function only uses the types?
Maybe the title is not clear, so concretely: #include <type_traits> template<typename T> constexpr int test(T) { return std::is_integral<T>::value; } int main() { constexpr int a = test(1); // right constexpr int b = test(1.0); // right int c = 2; constexpr int d = test(c); // ERROR! return 0;...
Just take T by reference so it doesn't need to read the value: template<typename T> constexpr int test(T&&) { return std::is_integral<std::remove_cvref_t<T>>::value; } You can even declare test with consteval, if you want to. (Note that stripping cv-qualifiers isn't necessary in this instance; cv-qualified integra...
73,550,199
73,550,276
How to catch a base class constructor's exception in C++?
I have a class that is derived from another class. I want to be able to catch and re-throw the exception(s) thrown by the derived class's constructor in my derived class's constructor. There seems to be a solution for this in C#: https://stackoverflow.com/a/18795956/13147242 But since there is no such keyword as C#'s b...
There is a pretty good example of this here: Exception is caught in a constructor try block, and handled, but still gets rethrown a second time Ultimately, if you manage to catch an exception in the derived class the only thing you should do is to either rethrow that exception or throw a new one. This is because if the...
73,550,443
73,550,472
why we can't initiaize data member in a member function using list initializer?
why assignment is working, but initialization not working ? please explain what is happening in these 3 cases in code. #include <iostream> class Fun { public: void set_data_variable() { y {2}; // case 1 : this doesn't work // y = 2; // case 2 : this does work // y = {2}; // case ...
For intrinsic type (And also user defined classes) this syntax: y {2}; Is only valid during object construction. The object y has already been constructed. It happened in the compiler generated function Fun() (The default constructor of the Fun class). y = 2; and y = {2}; work because they are assignment operations.
73,550,449
73,550,535
C++ Default Argument using Default Constructor to instantiate
Is it possible to have a function that takes a reference to an argument that has a default, where the default is instantiated using its default constructor? For example: void g(Foo &f = Foo()) {} This does not work, but I feel that it conveys my intention quite clearly.
References to non-const cannot bind to temporary values, and Foo() is a temporary Foo object. If you don't need to modify the passed object, then you can make f a reference to const: void g(const Foo& f = Foo()) {} If you do modify the passed reference, then using a temporary doesn't make much sense, since you'll woul...
73,550,544
73,550,728
How to use regex_iterator with const char/wchar_t*?
How to use the regex_iterator on data types of const char*/wchar_t*? From docs: using cregex_iterator = regex_iterator<const char*>; using wcregex_iterator = regex_iterator<const wchar_t*>; using sregex_iterator = regex_iteratorstring::const_iterator; using wsregex_iterator = regex_iteratorwstring::const_iterator; Re...
You have a few errors. Assuming you pass a const char* or const wchar_t*, T will be char or wchar_t, so: std::regex_iterator expects an iterator type, which neither char nor wchar_t are. You want to pass it const T* instead. *i will yeild a std::match_results<const T*> as well, so that's the type you should store in...
73,551,092
73,551,209
Change Nlohmann json key-value with increment function? c++
Instead of this: j["skills"]["atk"] = j["skills"]["atk"].get<int>() + 6; I want something like this: void json_inc(json ref, int value) //function to increment int key-values { ref = ref.get<int>() + value; } json_inc(j["skills"]["atk"], 6); //adds 6 Is this possible for nested json objects like above?
You are passing your json object by value. This means, that the object will, in fact, be duplicated in memory and whatever changes you make to the object will ceased to exist once you leave the scope of the function. To actually manipulate the variable you are passing (and this works for any kind of C++ variable), you ...
73,551,110
73,551,673
What is the use of throw() after a function declaration?
Throw is defined as a C++ expression in https://en.cppreference.com/w/cpp/language/throw. Syntactically, it is followed by an exception class name. For example: int a = 1, b = 0; if (b==0){ string m ="Divided by zero"; throw MyException(m); //MyException is a class that inherit std::exception class } Ho...
throw() is not a throw expression. It is a completely independent syntax construct that just happens to look the same (C++ likes to reuse keywords for multiple purposes instead of reserving more identifiers). The position where throw() is used in your examples is not a position where the grammar of the language expects...
73,551,252
73,551,378
No matching default constructor for static unique_ptr
I'm trying to use my custom functions for unique_ptr deletion. But the compiler gives me errors. Somehow I suspect that this is because my deleter is not a class type. But I swear it worked before with functions, I used to plug in C-functions just fine. What is the real deal? Demo #include <cstdio> #include <memory> #i...
You can't use a function type as template argument for the Deleter template parameter of std::unique_ptr. Use a function pointer instead: using tmp_storage_type = std::unique_ptr<cTYPE, decltype(&delete_wrapper)>; Because this would come with the potential pitfall that the value-initialized state of the deleter would ...
73,551,651
73,551,896
C++ EIGEN: How to create triangular matrix map from a vector?
I would like to use data stored into an Eigen (https://eigen.tuxfamily.org) vector Eigen::Vector<double, 6> vec({1,2,3,4,5,6}); as if they were a triangular matrix 1 2 3 0 4 5 0 0 6 I know how to do it for a full matrix using Eigen's Map Eigen::Vector<double, 9> vec({1,2,3,4,5,6,7,8,9}); std::cout << Eigen::Map<Eige...
In my opinion this cannot be done using Map only: The implementation of Map as it is relies on stride sizes that remain constant no matter their index positions, see https://eigen.tuxfamily.org/dox/classEigen_1_1Stride.html. To implement a triangular matrix map you would have to have a Map that changes its inner stride...
73,552,084
73,552,457
Is returning a reference to a pointer in a class defined behaviour?
Consider #include <iostream> struct Foo { int* n; Foo(){n = new int{};} ~Foo(){delete n;} int& get() { int* m = n; return *m; } }; int main() { Foo f; std::cout << f.get(); } This is a cut-down version of a class that manages a pointer, and has a method that returns a...
Is that defined behaviour? Yes, the given program is well-formed. You're returning a non-const lvalue reference that refers to a dynamically allocated integer pointed by the pointer n and m. The integer object still exists after the call f.get(). That is, itis not a function local variable. Note also that just retur...
73,552,906
73,553,217
Template argument deduction with designated initializers
I have the following peace of example code: #include <array> template<std::size_t N> struct Cfg { std::array<int, N> Values; // ... more fields } constexpr Cfg c = { .Values = { 0, 1, 2, 3 } }; Is it possible to deduce the template parameter N from the designated initializers? Using makeArray or initialize it w...
The designated initializer is not relevant here. For the purpose of class template argument deduction it is just handled as if it was a usual element of the initializer list. (At least that is how I read the standard. It is a bit unclear in [over.match.class.deduct] how a designated initializer ought to be handled when...
73,553,727
73,554,010
Comparator function for upper_bound or lower_bound for vector of vector
How(is it possible) to write a compartor function for upper_bound for a vector of vector such that it compares all indexes of inner vector and get a element in which corresponding element are larger For example for a given arr vector<vector<int>>arr={{0,1,1},{0,1,2},{0,2,1},{1,2,3},{4,1,2},{4,3,2}} the upper bound of ...
I will assume that the predicate you have in mind is "all values in the inner vectors must be greater". upper_bound requires a vector of data that is partitioned with respect to the given sample. In the given example, the data vector is not partitioned w.r.t. {0,1,1} (and the assumed predicated), hence, you cannot even...
73,553,856
73,558,241
What's the best way to pass an empty string as argument to boost::program_options?
I have a program that use boost::program_options to parse a command line. One of the parameter is the name of an AMQP exchange, and a default value is provided. For testing purposes, I would like to override this AMQP exchange name with an empty string (to use a default exchange). I don't know how to pass an empty stri...
To my surprise, the adjacent long option parser absolutely forbids the = sign with a zerolength value, see the code on https://github.com/boostorg/program_options/blob/develop/src/cmdline.cpp#L520. Therefore it seems your only recourse is to avoid using the adjacent-value syntax: for EXCHANGE in foo bar ''; do ./build/...
73,554,015
73,587,197
confusion about gluProject and OpenGL clipping
Consider the fixed transformation pipeline of OpenGL, with the following parameters: GL_MODELVIEW_MATRIX 0,175,303.109,0,688.503,-2741.84,1583,0,29.3148,5.52094,-3.18752,0,-87.4871,731.309,-1576.92,1 GL_PROJECTION_MATRIX 2.09928,0,0,0,0,3.73205,0,0,0,0,-1.00658,-1,0,0,-43.9314,0 GL_VIEWPORT 0,0,1920,1080 When I draw t...
I found the answer, in part thanks to this post. The explanation is that the 4 vertices that have y < 0 in screen space, are also behind the camera, and so have w_clip < 0. Perspective division (y_clip/w_clip) produces in turn a positive value in device independent coordinates and screen space.
73,554,051
73,554,109
Can I define a constructor from another one?
Here's a dummy example to illustrate: class C { // complex class with many fields and methods // including very expensive: int computeA(); int computeB(); } struct S { S(int a, int b); // initializes as {a, b, a*b}; // how to define below constructor? S(const C& c); // Should be equivalent...
This code does what you want S(const C& c) : S(c.computeA(), c.computeB()) {} It's called a delegating constructor and is available from C++11.
73,554,489
73,554,592
C++ override of nested class function
I have a class that derives from a base class, which has a nested class. I want to override a nested class's member function in my derived class and override a base class's member function. (as shown below) I found a solution (https://stackoverflow.com/a/11448927/13147242) that works by creating another nested class th...
It appears the issue is that in this line Base::Nested nested = derived.funcBase(); a copy of type Nested is created by a Nested::Nested(Nested&) copy constructor, out of derived object (DerivedNested). Then in nested.funcNested(); line a method is called on that copy object of parent class, thus no dynamic dispatch he...
73,554,574
73,564,518
Cosine interpolation Rendering as Linear Interpolation
I am trying to create different interpolation methods between points. So far I have got Linear interpolation Down, but my Cosine interpolation seems to be rendering as linear, so I have something very wrong. I am using C++ to code and SFML to render My linear interpolation function is: sf::Vector2f game::linearInterpol...
Ok so turns out I'm an idiot, LEARN FROM MY MISTAKE BEFORE YOU SPEND DAYS TRYING TO FIX THIS YOURSELF. DO NOT INTERPOLATE ON BOTH AXIS: sf::Vector2f game::cosineInterpolate(sf::Vector2f a, sf::Vector2f b, float randN) { float ft = randN * 3.1415927f; float f = (1 - cos(ft)) * 0.5f; return sf::Vector2f(a.x ...
73,554,630
73,567,018
ARCore's ArFrame_acquireCameraImage method returns green image
I'm trying to get image from camera using ARCore. I'm calling ArFrame_acquireCameraImage, which returns image with YUV_420_888 format. I also checked it using ArImage_getFormat method. It returns me 640x480 image. Then I obtain pixel stride for U plane to distinguish images with NV21 or YV12 format. Then I combine Y, U...
I replaced RenderScript Intrinsics Replacement Toolkit (which have multithreading and SIMD) with code taken from TensorFlow. I see this advantages: It's simpler. Here's attempt to use RSIRT: auto *yuv420 = new uint8_t[yLength + uLength + vLength]; memcpy(yuv420, y, yLength); memcpy(yuv420 + yLength, u, uL...
73,554,733
73,554,845
Syntax for declaring const member function returning a bare function pointer, without typedefs?
I have a class that stores a function pointer to some binary function class ExampleClass { private: double(*_binaryFunction)(double, double); } How can I return this pointer in a const "getter"? This is either surprisingly hard to search for or nobody else has asked this. If the function weren't const, the syntax ...
How can I return this pointer in a const "getter"? Examples: struct ExampleClass { double (*_binaryFunction)(double, double); double (*GetBinaryFunction() const)(double, double) { return _binaryFunction; } typedef double (*BinaryFunctionTypedef)(double, double); BinaryFunctionTypedef GetB...
73,555,327
73,555,762
Active member of an union after assignment
Suppose sizeof( int ) == sizeof( float ), and I have the following code snippet: union U{ int i; float f; }; U u1, u2; u1.i = 1; //i is the active member of u1 u2.f = 1.0f; //f is the active member of u2 u1 = u2; My questions: Does it have a defined behaviour? If not why? What is the active member of u1 ...
Does it have a defined behaviour? If not why? It has defined behaviour. The assignment copy the value of u2 and for me the value of an union is a designation of the active member (although that part is not represented and so can't be examined but it determines what is UB and what is not) and the value of the active...
73,555,398
73,556,546
Can I prevent the gcc optimizer from delaying memory allocation?
I have a program compiled with gcc 11.2, which allocates some RAM memory first (8 GB) on heap (using new), and later fills it with data read out in real-time from an oscilloscope. uint32_t* buffer = new uint32_t[0x80000000]; for(uint64_t i = 0; i < 0x80000000; ++i) buffer[i] = GetValueFromOscilloscope(); The problem I...
You seem to be misinterpreting the situation. Virtual memory within a user-space process (heap space in this case) does get allocated “immediately” (possibly after a few system calls that negotiate a larger heap). However, each page-aligned page-sized chunk of virtual memory that you haven’t touched yet will initially ...
73,555,493
73,555,660
Compiler error on member initialization of c-style array member (compared with std::array member)
I encountered this problem while initializing a member array variable (c-style). Interestingly converting the member into a std::array<> solves the problem. See below: struct A { A(int aa) : a(aa) {} A(const A &a) = delete; A &operator=(const A &a) = delete; private: int a; std::vector<int> v; }; struct B1...
Does it mean it's a GCC bug Yes, this seems to be a gcc bug that has been fixed in gcc 9.4. Demo. A bug for the same has been submitted as: GCC rejects valid program involving initialization of array in member initializer list
73,555,606
73,555,861
std::unordered_set<std::filesystem::path>: compile error on clang and g++ below v.12. Bug or user error?
I added the following function template to my project, and a user complained that it wouldn't compile on their system anymore: template<typename T> std::size_t removeDuplicates(std::vector<T>& vec) { std::unordered_set<T> seen; auto newEnd = std::remove_if( vec.begin(), vec.end(), [&seen](const T& valu...
The std::hash specialization for std::filesystem::path has only recently been added as resolution of LWG issue 3657 into the standard draft. It hasn't been there in the published C++17 and C++20 standards. There has always been however a function std::filesystem::hash_value from which you can easily create a function o...
73,555,760
73,555,871
Convert void function to std::function<void()>
I am having some trouble passing a callback function as an argument to a function. The function expects the following type: std::function<void(char* topic, byte* payload, unsigned int length)> But when I pass this function: void AMI_MQTT::Callback(char* topic, byte* payload, unsigned int length) It is not accepted si...
The problem here is that your function appears to be a non-static member function. Non-static member functions implicitly have additional parameter of an instance of the class they belong to, so the signatures of your std::function and the function you are trying to pass simply don't match. However you still can bind a...
73,555,847
73,556,339
Does assigning a vector variable to itself result in copy C++
Suppose I have a vector: std::vector<uint64_t> foo; foo.push_back(1); foo.push_back(27); I pass this vector to a function by reference. calculate_something(foo); int calculate_something(std::vector<uint64_t>& vec) { // ... } In rare circumstances, the function needs to locally modify the vector, in which case a co...
No, it is not correct. Assignment in C++ doesn't create new objects or change what object a reference refers to. Assignment only changes the value of the object to which the left-hand side refers (either through a built-in assignment operator or through the conventional behavior of operator= overloads). In order to cre...
73,557,265
73,557,302
Why is the address different?
I wrote the below code for my understanding of pointers. #include <cstdio> #include <iostream> using namespace std; int main() { string a = "hello"; const char *st = &a[0]; printf("%p\n", &st[0]); printf("%p\n", &(a[0])); printf("%c\n", *st); printf("%p", &a); } This is the output that I get 0...
A std::string is a C++ object, which internally holds a pointer to an array of chars. In your code, st is a pointer to the first char in that internal array, while &a is a pointer to the C++ object. They are different things, and therefore the pointer values are also different.
73,557,662
73,565,214
how can I achieve multiple conditional inheritance?
I have a type build that has a flag template, and according to the active flag bits, it inherits from those types. this allows me to "build" classes from many subclasses with a great number of configurations: #include <type_traits> #include <cstdint> struct A { void a() {} }; struct B { void b() {} }; struct C { void ...
Here's another approach using c++20 that provides much more flexibility for bitmask-based inheritance: #include <concepts> #include <cstdint> template <std::integral auto, class...> struct inherit_mask {}; template <auto flags, class Base, class... Bases> requires((flags & 1) == 1) struct inherit_mask<flags, Base, ...
73,557,680
73,557,862
c++ : How to pass a normal c function as hash functor for unordered_map
I've got this hash function is C style: static size_t Wang_Jenkins_hash(size_t h) { h += (h << 15) ^ 0xffffcd7d; h ^= (h >> 10); h += (h << 3); h ^= (h >> 6); h += (h << 2) + (h << 14); return h ^ (h >> 16); } Then I try to use it for unordered_map's hash parameter. Do I always need to write a ...
Functors are probably the easiest way to do this. When you use a free function the syntax becomes std::unordered_map<std::size_t, std::size_t, decltype(&Wang_Jenkins_hash)> but that is only half of what you need. Since we are using a function pointer type we need to pass to the map the function to use, and to do tha...
73,557,743
73,557,810
How to ensure that inheriting classes are implementing a friend function (ostream)?
I'd rather implement a non-friend function and directly mark the function as virtual. But I'm in a situation where I'd like to ensure that a specific set of classes implement an overloading of friend std::ostream& operator << (std::ostream& os, MyClass& myClass); and I found no other way to link it directly to my clas...
You can create a pure virtual method - that will require inherited classes to overload it, then make friend output operator to call it. For example: class MyClass { public: virtual ~MyClass(); virtual void output( std::ostream &os ) const = 0; friend std::ostream& operator << (std::ostream& os, const MyCla...
73,557,931
73,558,233
Convert C Cast Macro To C++ Function
I am working with a C library that uses the usual C "inheritance" trick typedef struct Base_ *BasePointer; struct Base_ { }; typedef struct Derived_ *DerivedPointer; struct Derived_ { Base_ header; }; #define BaseCast(obj) ((BasePointer)(obj)) void bar(BasePointer); void foo(DerivedPointer derived) { bar(BaseCa...
Post this as answer because discussion in comments got stuck somehow and I don't see why it is not an alternative. Return the pointer by value: template <typename T> [[nodiscard]] static inline constexpr BasePointer BaseCast(const T& object) noexcept { static_assert(util::convertible_to_base<T>::value, ""); return ...
73,558,239
73,593,775
How to calculate the possible number of sub-string that are palindrome. But substring that are unique?
template <class T> int subPalindrome(T s) { int res = 0; for (int i = 0; i < str.length(); i++) { for (int j = 0; (j + i) < str.length() && (i - j) >= 0; j++) { if (str[i + j] != str[i - j]) { break; ...
int subPalindrome(T s) { int n = s.size(); // dp array to store whether a substring is palindrome // or not using dynamic programming we can solve this // in O(N^2) // dp[i][j] will be true (1) if substring (i, j) is // palindrome else false (0) vector<vector<bool> > dp(n, vector<bool>(...
73,558,352
73,558,730
operator== idiosyncrasies between std::variant and std::shared_ptr?
The automatically instantiated operator== for my std::variant<> interferes with one of its variations, which is a std::shared_ptr<>. My actual variant has about 12 different possible alternatives, but to keep it short, here I just show a trivial example: #include <iostream> #include <string> #include <vector> #include ...
std::shared_ptr<T>::operator== compares the pointers. Thats what it should do (irrespective of being in a std::variant or not). If you want to compare the pointees, then you do not want std::shared_ptr, at least not a naked one. You can use a custom class: struct my_shared_int { std::shared_ptr<int> value; /...
73,558,440
73,558,480
How does an std::string field in a struct gets written to an std::fstream?
Here is an example struct: struct Person { std::string Name; int Age; }; And Here is how i write it to an fstream: Person p; p.Name = "Mike"; p.Age = 21; stream.write((char*)&p, sizeof(p)); As you can see above I write my Person variable to an fstream using write() function. Person's name is written to the s...
There is no special magic here. Try a larger string (say a few lines of lorem ipsum), and you will find the same thing happens as const char* (with a few extra data points like size and capacity). This behavior comes from the Small String Optimization. For short strings, the characters are actually stored inside the st...
73,558,789
73,570,836
Unable to deduce template arguments when using parameter pack in a member function argument
Why does compiler fail to deduce arguments types in this case ? class MyArrayOfObjects{ //assume this class contains a buffer of ObjectInArray template<typename ObjectType, typename ... ParamsT> inline void foreach(ObjectType* obj,void(ObjectType::* func)(ObjectInArray *, ParamsT&&... ), ParamsT&&... para...
The parameter is: void(ObjectType::* func)(ObjectInArray *, ParamsT&&... ) That accepts a member function pointer which takes one pointer argument followed by arbitrary rvalue reference arguments. The call is: myArray.foreach(myOtherObject, &MyOtherObjectType::callThatInLoop, 10, "hello world"); That is trying to pa...
73,559,359
73,559,413
OpenGL, render to texture with floating point color without clipping value
I am not really sure what the English name for what I am trying to do is, please tell me if you know. In order to run some physically based lighting calculations. I need to write floating point data to a texture using one OpenGL shader, and read this data again in another OpenGL shader, but the data I want to store may...
The type and format arguments glTexImage2D only specify the format of the source image data, but do not affect the internal format of the texture. You must use a specific internal format. e.g.: GL_RGBA32F: glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
73,559,849
73,559,992
How to reserve a vector of strings, if string size is variable?
I want to add many strings to a vector, and from what I've found, calling reserve() before this is more efficient. For a vector of ints, this makes sense because int is 4 bytes, so calling reserve(10) clearly reserves 40 bytes. I know the number of strings, which is about 60000. Should I call vector.reserve(60000)? How...
The compiler doesn't know the size of the strings, it knows the size of std::string object. Now, the size of std::string object does not depend on size of string. That is because - most of the time [1] - std::string will allocate on heap, so the object itself is only a pointer and length. This also means, when you rese...
73,559,895
73,560,267
Using template type as argument to std::invoke
Consider this code: using namespace std; struct FS { void print() { cout << "p\n"; } int s; }; template <typename T, typename F> void myInvoke(T& t, F f) { invoke(f, t) = 10; } int main(int, char**) { FS fs; myInvoke(fs, &FS::s); cout << fs.s << "\n"; } Is there anyway to avoid the runti...
It seems you are looking for deduced Non-type template parameter (with auto) (C++17): template <auto F, typename T> void myInvoke(T& t) { invoke(F, t) = 10; } with usage: myInvoke<&FS::s>(fs); Demo
73,560,209
73,567,195
boost:asio::write writes to socket successfully, but server doesn't see the data
I've written a simple code sample that writes some data to the socket towards a simple TCP echo server. The data is written successfully to the socket (writtenBytes > 0), but the server doesn't respond that it has received the data. The application is run in a Docker devcontainer, and from the development container, I'...
It turned out the issue was with the Docker container that received the message. The image istio/tcp-echo-server:1.2 doesn't write to logs unless you send the data with \n in the end.
73,560,455
73,560,819
How to handle a PostMessageThread message in std::thread?
Somewhere in my main thread I am calling PostThreadMessage(). But I don't know how to handle it in the std::thread I have sent it to. I am trying to handle it in std::thread like this: while(true) { if(GetMessage(&msg, NULL, 0, 0)) { // Doing appropriate stuff after receiving the message. } } And I am ...
What std::thread::native_handle() returns is implementation-defined (per [thread.req.native] in the C++ standard). There is no guarantee that it even returns a thread ID that PostThreadMessage() wants. For instance, MSVC's implementation of std::thread uses CreateThread() internally, where native_handle() returns a Win...
73,561,029
73,561,541
Passing std::move(obj) as an argument to a call to obj's own method
Context: I have a singly-chained list of Nodes, and calling PruneRecursively on its root should prune certain nodes from it, preserving the rest of the chain. Each node knows privately whether it should stay or go. The implementation I came up with looks as follows: unique_ptr<Node> Node::PruneRecursively(unique_ptr<No...
Since C++17 it is guaranteed that the postfix expression in a function call is evaluated before any of the expressions in the argument list. That means operator-> on m_RootNode is guaranteed to be evaluated before the constructor of self is called. Therefore there is technically no problem. Before C++17 there was no gu...
73,561,144
73,561,490
log4cplus ConsoleAppender does not work in container
I'm trying to containerize my application but I'm having trouble getting log4cplus working. Bottom line up front, logging works when running on the host, but not in the container when I'm logging from long running loops. Its seems like a buffer somewhere is not getting flushed. A minimal example follows. Additionally, ...
Not sure why, but adding log4cplus.appender.MyConsoleAppender.ImmediateFlush=true to log4cplus_configure.ini solved my issue.
73,561,571
73,561,689
How to capture a function in C++ lambda
I'm wondering how I can pass a function in the capture list. My code snippet is shown below. It aborts with error: capture of non-variable ‘bool isVowel(char)’. Why does this similar posted solution with a function pointer work? #include <iostream> #include <algorithm> #include <set> #include <list> using namespace std...
Why does this similar snippet work? Because in that snippet: auto func(void(*func2)()) { return [&func2](){cout<<"hello world 1"<<endl;func2();}; } func2 is a local variable with type pointer to a function. In your case you are trying to capture a function itself which is not allowed: The identifier in any capt...
73,561,670
73,561,737
Best practice: [[maybe_unused]] or anonymous argument?
Let's say I have a class with a virtual function with one argument and two different implementations of this virtual function. The first implementation uses the argument while the second does not. The second case will produce a compilation warning. There are two ways I can think of to suppress the warning. Using an an...
The most authoritative source we have for "best practice" in C++ is the C++ Core Guidelines. And on the topic of unused arguments, they have this to say F.9: Unused parameters should be unnamed ... If parameters are conditionally unused, declare them with the [[maybe_unused]] attribute. So the C++ Core Guidelines rec...
73,561,731
73,561,776
How to check if a number is in a vector, and if not, then to return -1?
This is pretty easy if I can import <algorithm> or any other things at the top, but I just started using C++ and my professor asked us to use only loops and conditionals for this problem. The problem itself is to give a vector v and an int seek to a function. A loop runs through the vector to find the index of the firs...
You have the return -1; statement in the wrong place. It needs to be after the loop exits, not inside the loop. For example: int find(const std::vector<int>& v, int seek) { for (int i = 0; i < v.size(); i++) { if (seek == v[i]) { return i; } // else { // return -1; ...
73,563,545
73,563,628
Number of class template instantiations
I was wondering whether you should worry about the number of class template instantiations and their effect on compile times. In the below example, I imagined that the Foo template would only be instantiated only once, while the Bar template would be instantiated twice. Do such differences matter to STL writers? templa...
So the simple answer is that the generation of template code (and subsequent compilation) will occur for each type you are creating. So in this example: Bar<1> bar1; Bar<1> bar2 ... Bar<1> bar10000; Each of these are of type Bar<1> so you only need to generate the code for Bar<1> once. You can see this in the cpp insi...
73,563,894
73,579,169
Run virtual environment using VMX in C++
I was curious if it's possible to start a virtual environment that can do something like this: int main() { std::cout << "This part is being ran on the host"; StartVM(); std::cout << "This part is being ran on a VM"; EndVM(); return 0; } I've read on some documentation on Intel-VT's VMX operations, but i...
A research paper called dune implements what you describe. Paper: https://www.usenix.org/conference/osdi12/technical-sessions/presentation/belay Open Source Code: https://github.com/project-dune/dune It achieves so with a kernel module that handles VM entries/exits and syscall forwarding. It also applies a bunch of (...
73,564,242
73,564,835
Shall I try to use const T & as much as possible?
I am learning books <Effective C++>, i think use const reference is a good practice. because it can avoid unnecessary copy. so, even in initialize a object, i use const T & t = T(); here is the code: #include <string> #include <iostream> #include <vector> using namespace std; template <class T> inline std::vector<std...
const std::string& str = "myname@is@haha@"; This works due to reference lifetime extension. When a prvalue is bound immediately to a reference-to-const or an rvalue reference its lifetime gets extended to the lifetime of the reference. Since "myname@is@haha@" is not a std::string, a temporary std::string gets constr...
73,564,321
73,564,382
Resetting unique_ptr to an array of characters
I'm porting an old C++ program to modern C++. The legacy program uses new and delete for dynamic memory allocation. I replaced new with std::unique_ptr, but I'm getting compilation error when I try to reset the unique_ptr. Here is the striped down version of the program. My aim is to get rid of all the naked new. #incl...
If you look at the reset function, it takes a ptr to memory, not another unique ptr: // members of the specialization unique_ptr<T[]> template< class U > void reset( U ptr ) noexcept; This function is designed to allow you to reset a unique pointer and simultaneously capture memory that you intend to manage with said ...
73,564,414
73,564,480
Time complexity in c++. loops
I have been learning DSA, but calculating time complexity is a little difficult I understand the logic of O(n^2) or O(n) but what will be the time complexity of and how?: while(n%2 == 0) { n/=2; } It will be O(n/2)? not sure
You can test it practically to see how much iterations loop will have depending of n int main() { int n = 2048; int count = 0; while(n%2 == 0) { n/=2; ++count; } std::cout << count; return 0; } So, when n = 1024, count = 10 when n = 2048, count = 11 2^(iteration count) = N; So,...
73,564,472
73,571,384
how to cast one type to another while preserving value category and cv-qualifiers?
As the title says. C++ already has std::forward, but it can't cast the original type to another. I wonder if there is a function to cast one type to another while preserving the value category and cv-qualifers of the original type. Supposing there is such a function called perfect_cast to do the magic, the output of th...
There aren't a lot of use cases for a combined conversion-forward. Arguably, most casts result in prvalues, and for derived-to-base casts, the language already permits treating the derived as base, preserving value category. For example, the OP main would be more clearly written as: B<0, 1, 2, 3> b; auto& b1 = b; b1.A<...
73,565,363
73,572,122
Getting tbb linker errors when including the <execution> header
I have been writing a visualisation tool using OpenGL. It has been compiling and linking just fine (using gcc 11.2.0) until I recently installed the Linux dependencies for OpenVDB (listed under Using UNIX apt-get). I am now getting linker errors that I have narrowed down to the inclusion of the <execution> header file:...
I have managed to successfully link tbb as follows: find_package(TBB REQUIRED COMPONENTS tbb) add_executable(test main.cpp) target_link_libraries(test tbb) Although I am still clueless as to why I suddenly needed to link with tbb, considering I previously didn't need to.
73,565,441
73,565,787
C++ | Input the following string inside a rectangle
I would like to input the following code inside a rectangle, so that the output would be the rectangle with my printed text. Here is my code: #include <iostream> using namespace std; int main() { cout <<" * Programming Assignment *" << endl; cout <<" * Data Structures *" << endl; cout <<" * Author: Hel...
You can use #include <iomanip> header, which includes convenient objects which you can pass into cout, to manipulate the output: std::setw(width) to specify that the next thing you print (text in our case) will have to be padded to have exactly width characters, std::setfill(' ') to specify with which character you pad...
73,565,975
73,566,036
no known conversion from 'std::shared_ptr<int>' to 'int *' for 1st argument
when operating smart pointers, something confused me. Hers is the error message no known conversion from 'std::shared_ptr<int>' to 'int *' for 1st argument and here's the code I ran #include <memory> #include <vector> class test { public: int x_; test(int *x) {} }; int main(int argc, char *argv[]) { auto x = ...
Use x.get(). It's not implicitly convertible because that would make it too easy to make mistakes, like creating another shared_ptr from the same raw pointer without proper sharing.
73,566,127
73,569,488
How do applications determine if instruction set is available and use it in case it is?
Just interesting how it works in games and other software. More precisely, I'm asking for a solution in C++. Something like: if AMX available -> Use AMX version of the math library else if AVX-512 available -> Use AVX-512 version of the math library else if AVX-256 available -> Use AVX-256 version of the math library e...
For the detection part See Are the xgetbv and CPUID checks sufficient to guarantee AVX2 support? which shows how to detect CPU and OS support for new extensions: cpuid and xgetbv, respectively. ISA extensions that add new/wider registers that need to be saved/restored on context switch also need to be supported and ena...
73,566,210
73,566,251
Move semantics and std::move
I have a general question about move semantics. Yesterday I just played around to get more comfortable with this topic. Here I added copy and move constructor operators, that simply log to the console: #include <iostream> class Test { public: const char* value = "HI"; Test(){ std::cout << "Default Constru...
But why wasn't the Test's move constructor operator be called? Because you keep operating on the same object via a reference to an rvalue. No new object is being constructed, hence no constructor is necessary. You could conceivably keep passing that reference down, just like you can do with a regular reference or a r...
73,566,320
73,567,901
boost beast sync app - Is explicit concurrency handling needed?
Consider the official boost beast websocket server sync example Specifically, this part: for(;;) { // This buffer will hold the incoming message beast::flat_buffer buffer; // Read a message ws.read(buffer); // Echo the message back ws.text(ws.got_text()); ws.write(buffer.data()); } To sim...
Yes, you need synchronization because you access the object from multiple threads. The documentation you quoted is very clear on that: Sharedobjects:Unsafe [...] On your rationale for being confused: This seems to imply ws object is not thread-safe, but also for the specific case of a sync app, there's no explicit s...
73,566,585
73,569,548
How to programmatically get the name of the current printer through the libcups in Linux?
I'm trying to get the name of the current printer using the libcups library in Linux, but I can't find such a method. I found only how to get a complete list of printers, but how to find out which one will print is not clear. #include <cups/cups.h> QStringList getPrinters() { QStringList printerNames; cups_d...
Once you have a valid destination (cups_dest_t), one can retrieve the informations via: cupsGetOption Example (from https://openprinting.github.io/cups/doc/cupspm.html#basic-destination-information): const char *model = cupsGetOption("printer-make-and-model", dest->num_options, ...
73,566,710
73,566,866
How to instantiate a pushbutton from ui into the code in QT framework
What I intent to do is just a basic animation in my qt application. For the animation, when the button is clicked, I want it to go from one point to another in a time interval. Here is my code (main.cpp and mainWindow.h are the same as default. ): MainWindow.cpp #include "mainwindow.h" #include "ui_mainwindow.h" #inclu...
You are declaring the anim object as local variable. As soon as on_pButton_clicked() function exits, anim variable will get destroyed. Create anim object on the heap, as shown below, then your code should work fine. void MainWindow::on_pButton_clicked() { QPropertyAnimation *anim = new QPropertyAnimation(ui->pButto...
73,568,020
73,607,202
C++ - Declare variable with a variable template list without "auto"
I am using c++17 and I need to declare some variables that has the following type structure: ctre::regex_results<const char*, ctre::captured_content<1, void>, ctre::captured_content<2, void> > mts; ctre::regex_results<const char*, ctre::captured_content<1, vo...
It seems you want a typedef to shortened ctre::regex_results<const char*, ctre::captured_content<1, void>, .., ctre::captured_content<N, void>> You might use decltype: decltype(search_rgx1("")) mts1; decltype(search_rgx2("")) mts2; Alternatively, you might use (global scope): template <typename Seq> struct regex_resul...
73,568,343
73,568,378
VS2022: std::string.c_str() Dangling pointer warning
I am getting a dangling pointer warning from VS2022 for this code snippet: chars = (unsigned char*)(pProgram->getProgramUUID().c_str()); memcpy(&outputBuffer[bufferPosition], chars, numChars); Warning Warning C26815 The pointer [chars] is dangling because it points at a temporary instance which was destroyed. getPro...
Because getProgramUUID() returns a string by value, that string object will be destructed and cease to exist once the full expression (the assignment) is finished. The pointer to the contained string will become immediately invalid. As a workaround you could call getProgramUUID() as part of the memcpy call: memcpy(&out...
73,569,146
73,569,841
DLL C++ import functions to Delphi
How do I access the functions of a C++ DLL in Delphi #define CCONV _stdcall typedef struct{ unsigned long BaudRate; unsigned char PortNumber; ..... }SSP_COMMAND; NOMANGLE int CCONV OpenSSPComPort (SSP_COMMAND * cmd); In documentation: OpenSSPComPort Parameters: Pointer to SSP_COMMAND structure ...
According to the C definition from the link you provided, you would need to change the following: type SSP_FULL_KEY = packed record FixedKey : UINT64; EncryptKey : UINT64; end; type SSP_COMMAND=packed record key : SSP_FULL_KEY; BaudRate:integer; PortNumber:integer; SSPAddress : byte; ...
73,569,199
73,569,303
Switch betweeen method versions
I need to rewrite some c++ classes and I would like to be able to switch between the new code and the old code (reliable and fast). What would be good options to do so? In general I need some kind of switch that decides what to do, like: int foo::bar() { if (yesUseNew == true) { return 1 + 1; } else { ...
Well, I see the following alternatives : At compile time with #define e.g: #define V1 //Comment this line if you want V2. You can also define it on the command line of your compiler void myfunction() { #ifdef V1 //V1 Implementation #else //V2 Impl #endif At runtime with env variables for example This means you c...
73,569,323
73,569,630
Direct initialization with prvalue: Bug in MSVC?
Consider the following code: struct S { S(int, double) {} explicit S(const S&) {} explicit S(S&&) {} }; void i_take_an_S(S s) {} S i_return_an_S() { return S{ 4, 2.0 }; } int main() { i_take_an_S(i_return_an_S()); } With the '-std=c++17' flag, both g++ and clang++ compile this code just fine. MSVC ...
Yes, MSVC seems to be wrong here. Generally, since C++17, the initialization rules are so that S{ 4, 2.0 } will directly initialize the parameter S s of the function. (mandatory copy elision) There is however an exception. An implementation is allowed to introduce a copy in a function parameter or a return value if the...
73,569,633
73,572,092
Preventing network call while calling `date::make_zoned()`
While connected to the web, the following program, which converts a given std::chrono::system_clock::time_point to a string, takes a whopping 1s32ms to complete. However, if my machine is not connected to the web, the program requires a reasonable 54ms. #include "date/tz.h" // Howard Hinnant's date library #include <ch...
The documentation for Howard Hinnant's date library explains remote_version(), explains what it is for, and how to turn it off. I'll quote from the documentation: The following functions are available only if you compile with the configuration macro HAS_REMOTE_API == 1. Use of this API requires linking to libcurl. AUT...
73,569,666
73,570,610
How can I create a 20x80 board using a dynamic array?
I have to do Conway's Game of Life. I need to create a 20x80 board using a dynamic array (institutional requirements). const int ROWS = 20 const int COLUMNS = 80 void createBoard(char board[ROWS][COLUMNS]){ for(int i = 0; i < ROWS; i++){ for(int j = 0; j < COLUMNS; j++){ board[i][j] = ' '; ...
In the following code snippet function createBoard dynamically allocates and initializes the board as 2D array in row-major order. Function deleteBoard deallocates the board. const int ROWS = 20; const int COLUMNS = 80; char ** createBoard( void ) { //allocate array of pointers to board's rows char ** board = ...
73,570,084
73,576,563
Overalignment of an existing type in c++17
Given an existing type T, it is possible to overalign it on the stack with the alignas() keyword: alignas(1024) T variable; For dynamic allocation, we have a cumbersome syntax : T *variable = new (std::align_val_t(1024)) T; However, there are two problems with this syntax: Microsoft's compiler emits error C2956 ...
It is not possible to achieve the equivalent of your hypothetical: using AlignedType = alignas(32) T; There is no such thing as a type that is equivalent to another type but with different alignment. If the language allowed something like that to exist, imagine all the extra overload resolution rules we would have to ...
73,570,188
73,570,316
shared_ptr to derived class from a specific base class
I feel like this is a pretty basic C++ question. I am trying to make a class which contains a member variable which is a shared_ptr to any class which is derived from a specific interface, but does not care which particular derived class it is. I am implementing it as follows: class Base { public: Base(); virtual ...
Fixed the access specifiers and more: #include <memory> class Base { public: Base() = default; // must have implementation // virtual dtor - not strictly needed for shared_ptr: virtual ~Base() = default; virtual void do_stuff() = 0; }; class Derived : public Base { // public inheritance...
73,570,415
73,570,448
Range based for loop iteration on std::map need for explanation
The following code is running properly #include<iostream> #include<map> #include<algorithm> #include<string> #include<vector> using namespace std; int main() { std::map<int, std::string> m; m[0] = "hello"; m[4] = "!"; m[2] = "world"; for (std::pair<int, std::string> i : m) { cout << i.s...
The key in map cannot be changed, so if you take key-value pair by reference key must be const. In your example int variable is a key, if you take pair by reference, you could modify that key, which cannot be done with map. Take a look at map::value type: https://en.cppreference.com/w/cpp/container/map.
73,571,042
73,571,165
Clarification of rationale for not having tentative definitions
C++17 (N4713), C.1.2 Clause 6: basic concepts, 1: Change: C++ does not have “tentative definitions” as in C. Rationale: This avoids having different initialization rules for fundamental types and user-defined types. Question: what are the different initialization rules for fundamental types and user-defined types? An...
The preferred way to declare things with file scope is an anonymous namespace. Everything inside namespace {} has file scope. You can declare functions, classes, variables, etc. extern works as usual to declare a. Note that in C++ it's not necessary to write struct X struct X { int i; X* next; }; namespace { extern...
73,571,223
73,573,059
Using JNI with kotlin gives UnsatisfiedLinkError
I'm trying to use JNI with kotlin to use c++ code in kotlin, but for some reason im getting an UnsatisfiedLinkError even though the signature should be alright since its generated using javah. Any ideas why it would do that? Kotlin Function Declaration: external fun initLuaScript(script: String); javah generated head...
I figured out the problem! The problem was that i did not load the Native DLL. Basically i had the library load when the "Main" library class was loaded but i happened to execute a function before the actual DLL load, which caused the error!