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,239,675
70,248,097
How can I profile a MEX function written using the matlab editor and compiled using gcc
I'd like to profile a mex function I've written in the matlab (2021a) editor. The best I can do right now is to using matlab's tic, toc functions to measure total execution time, but I dont know how to use more detailed diagnostic tools to evaluate the code performance. I've found other questions and responses discussi...
There were two solutions I decided to pursue for this. Number one was adding timers to my code as suggested in the comments above (stackoverflow.com/a/47888078/7328782). You can then program your script to output the values to the matlab console using the following code snippet: std::ostringstream stream; ...
70,239,789
70,240,121
Am I correct about how this C++ code works?
In this code : class iop { public: iop(int y) { printf("OK\n"); } iop() { printf("NO\n"); } }; int main() { line 1- iop o; line 2- o = 8; line 3- return 0; } My conclusion of the way this C++ code work with is: Create an obj...
The class iop has implicitly defined copy and move constructors and assignments. o = 8; This will attempt to call operator=. As I've stated the copy and move assignment operators are implicitly defined: iop& operator=(const iop&); iop& operator=(iop&&); Because iop is implicitly constructible from int, both operators...
70,239,890
70,239,914
What is the difference between iterator and v.begin() method in STL?
#include <iostream> #include <vector> using namespace std; int main(void){ vector<int> v = {1, 2, 3}; auto& it = v.begin(); // 1. v.begin() += 1; cout << *(v.begin()); // output is 1 // 2. cout << *(v.begin()+1); // output is 2 } The upper code shows that v.begin() += 1; doesn't work as...
Is v.begin() lvalue or rvalue? It's an rvalue. auto& it = v.begin(); This is ill-formed because an lvalue reference to non-const cannot be bound to an rvalue. v.begin() += 1; This advances the temporary iterator to the beginning, and discards the result. It "works" if the goal is to do nothing useful. cout <<...
70,239,955
70,240,051
Calculating the number of elements in an array using pointer arithmetic
I have come across a piece of example code that uses pointers and a simple subtraction to calculate the number of items in an array using C++. I have run the code and it works but when I do the math on paper I get a different answer. There explanation does not really show why this works and I was hoping someone could e...
You forgot a small detail of how pointer addition or subtraction works. Let's start with a simple example. int *p; This is pointing to some integer. If, with your C++ compiler, ints are four bytes long: ++p; This does not increment the actual pointer value by 1, but by 4. The pointer is now pointing to the next int. ...
70,240,164
70,240,441
Detected memory leaks in c++
The following declaration in the file generated by grpc (grpc.pb.cc) causes a memory leak. It seems that google::protobuf::ShutdownProtobufLibrary() does not free the memory allocated by this declaration. Would you tell me how to release it? PROTOBUF_ATTRIBUTE_INIT_PRIORITY static ::PROTOBUF_NAMESPACE_ID::internal::Add...
The static or global object is freed the very last thing, after atexit, and the debugger reports false leak. This behavior can be reproduced with this example: #include <Windows.h> std::string str; int main() { _CrtDumpMemoryLeaks();//str is not freed yet return 0; } You can create a structure and place the l...
70,240,221
70,240,270
What is the right way to assign 0xFFFFFFFF to an unsigned integer variable?
If I compile following code size_t a = -1; with MSVC with W4 option I get warning C4245: 'initializing': conversion from 'int' to 'size_t', signed/unsigned mismatch and I am not 100% sure that -1 is 0xFFFFFFFF on all the platforms. Is -1 bit representation defined by the standard? Other options are: size_t a = std::n...
size_t a = -1; This will initialize a with the biggest value size_t can hold. This is defined in terms of modulo arithmetics and not bit patterns. So this is true regardless if signed integers use 2s complement or something else. Unsigned integers are required to be encoded directly as their binary representation so th...
70,240,467
70,240,482
Warning in C++: Pointer holds a value that must be examined when trying to assign new int32_t
I was trying to learn dynamic memory allocation in C++. My program compiles and works, but Visual Studio throws these warnings at me. What do they mean? Warning C28193 'ptr' holds a value that must be examined. Warning C28182 Dereferencing NULL pointer. 'ptr' contains the same NULL value as 'new(1*4, nothrow)' My c...
new (std::nothrow) int32_t Attempts to allocate the memory for int32_t, and if it cannot, it doesn't throw an exception, it returns nullptr. You go ahead and assign a number (10) to it, but you need to first determine if the memory allocation succeeded by checking if ptr is nullptr or not before assigning the value. I...
70,240,586
70,243,331
I keep getting an "error: constexpr variable 'x' must be initialized by a constant expression" from previously used working code
I've been scratching my head for days now. Gone step by step removing and adding lines and recompiling at each stage until it breaks. ACTION act1(name nm, uint64_t amount); ACTION act2(name nm, uint64_t signing_value); ACTION receiverand(name nm, checksum256& random_value); ACTION act4(name nm, uint64_t stake);...
Appears that a name cannot contain the character '6', but only '1' thru '5'. Action names [...] May contain: a-z, 1-5, or . https://eosio.stackexchange.com/questions/7/what-are-naming-rules-for-actions-tables-and-contracts
70,240,823
70,240,884
I can't store the address of Derived class in the pointer of base class when inheritance is private, but when I inherit it in public it shows no error
I am stuck with this code, when I store the address of the the Derived class in Pointer of base class, it shows error, but when made inheritance public there is no error, can anyone help..? #include <iostream> using namespace std; class Base // Created a Class Base { public: void show() { cout << "base"; } }; class De...
In your case the class Base is not accessible and $11.2/5 states - If a base class is accessible, one can implicitly convert a pointer to a derived class to a pointer to that base class (4.10, 4.11). [ Note: it follows that members and friends of a class X can implicitly convert an X* to a pointer to a private or prot...
70,241,162
70,241,300
How does the C++ compiler find operator overloading?
I have been looking into examples of operator overloading and some will include code snippets such as ostream& operator<<(ostream& os, const Date& dt) { os << dt.mo << '/' << dt.da << '/' << dt.yr; return os; } The ostream& operator<<(ostream& os, ...) seems to placed, for what atleast seems "randomly" around ...
You can simply define as an inline as you did std::ostream& operator << ( ostream& os, const Date& dt ) { os << dt.mo << '/' << dt.da << '/' << dt.yr; return os; } But you have to include this header before you use it, otherwise the C++ compiler will not know. Or you can define as a friend inline inside the cl...
70,242,045
70,242,528
Detecting the first digit in the second digits?
Needle in the haystack. I'm a beginner in programming and we only learned a thing or two so far, barely reached arrays yet. Input: 1 4325121 Output: 2 Input two values in one line. The first one shall accept any integer from 0-9 and the other one shall take a random positive integer. Using a while loop, count how man...
As you said, you need to keep it as simple as possible. Then this can be a solution: #include <iostream> int main() { int first { }; int second { }; std::cin >> first >> second; int quo { second }; int rem { }; int count { }; while ( quo > 0 ) { rem = quo % 10; quo /=...
70,242,089
70,249,725
Using std::less for a set of pointers
I've a some class where I'm declaring a set like this: std::set<UPFIR::RetentionSignal*> _retSignalSet; I'm trying to use std::less compare function on it. I tried something like this: std::set<UPFIR::RetentionSignal*, std::less<UPFIR::RetentionSignal*>> _retSignalSet; The feedback I'm getting is "adding std::less ...
If the requirement is that the set should be sorted by name, then std::less does not help. You must provide a custom comparator that compares the name. For example (just an untested sketch): struct LessByName { bool operator<(UPFIR::RetentionSignal* a, UPFIR::RetentionSignal* b) { return a->name < b->na...
70,242,118
70,249,702
g++ - not reflecting changes made in source file
I'm building a project with a structure like this: - Makefile - main.cpp - util.h - subsrc/ - one.cpp - two.cpp And I have my Makefile set up to output to a build directory: all: $(BIN_FILE) $(BIN_FILE): $(OBJ_FILES) mkdir -p $(BIN_DIR) g++ $^ -o $@ $(OBJ_DIR)/%.o: %.cpp mkdir -p $(OBJ_DIR) g++ -...
Your problem is that your code is weirdly written and as a result, your makefile is incomplete. In your main.cpp you have: #include "subsrc/derived.h" which is fine but in that header you have: #include "one.cpp" #include "two.cpp" which is extremely bizarre. You pretty much never want to include .cpp files in other...
70,243,298
70,247,227
What is the point of two types of module files (interface and implementation) in C++20?
When I want to export something I write export void foo(); I can implement it in the same module file or do it in a separate one. But what is the point of formally distinguishing these files (export module mymodule vs module mymodule) when, anyway, I can have any number of the latter type. Wouldn't be enough to just pu...
At some point, the build system sees that some file says import MyModule;. When it sees that, the build system needs to go find the module for MyModule. If MyModule has not yet been built, the build system needs to build it. To do that, it has to (among other things) scan all of the known source files in your project t...
70,244,490
70,245,497
Optimization of image resizing (method Nearest) with using SIMD
I know that 'Nearest' method of image resizing is the fastest method. Nevertheless I search way to speed up it. Evident step is a precalculate indices: void CalcIndex(int sizeS, int sizeD, int colors, int* idx) { float scale = (float)sizeS / sizeD; for (size_t i = 0; i < sizeD; ++i) { int index = (i...
I think that using of _mm256_i32gather_epi32 (AVX2) can give some performance gain for resizing in case of 32 bit pixels: inline void Gather32bit(const uint8_t * src, const int* idx, uint8_t* dst) { __m256i _idx = _mm256_loadu_si256((__m256i*)idx); __m256i val = _mm256_i32gather_epi32((int*)src, _idx, 1); _...
70,244,805
70,245,700
When does reference casting slice objects?
Take a look at this piece of code: #include <iostream> class A{ public: int x; virtual void f(){std::cout << "A f\n";} }; class B: public A { public: int y; void f() {std::cout << "B f\n";} }; void fun( A & arg) { std::cout << "fun A called" << std::endl; arg.f(); // ar...
Yes, you seem to have got this. :-) A B is also an A (by inheritance), so it can bind to either A& or B&. Nothing else happens, it is just a reference to the existing object. The slicing happens if you assign a B object to an A object, like A a = b;, which will only copy the inherited A portion of b.
70,244,992
70,245,047
Why is using a reserved identifier name in constexpr context not diagnosed?
Based on the following two rules: Using an identifier starting with "_" + capital letter, or containing double underscore, is undefined behavior. Undefined behavior is not allowed in constexpr expressions -> compiler should not compile. Then why aren't compilers complaining about this? constexpr int _UB() {return 1;}...
Undefined behavior is not allowed in constexpr expressions -> compiler should not compile It's a bit more narrow than this; as per [expr.const]/5, /5.7 in particular: An expression E is a core constant expression unless the evaluation of E, following the rules of the abstract machine ([intro.execution]), would evalu...
70,245,044
70,245,791
What cause undefined behavior when converting from unsign int to sign int and print it out
I have the following codes: #include "stdio.h" #include "stdint.h" #include <string> #include "string.h" #include<iostream> using namespace std; class myMessage { public: uint8_t latitude[4]; //Binary uint8_t longitude[4]; //Binary }; int8_t sentMessage[4]={0,}; int main()...
The program prints out FFFFFF82 with some extra Fs because of printf. Printf takes %x and assume that I will pass into it value unsigned int which has 8 bytes. 0x82 with int8_t is unsign 8 bits, or 1 byte. Since printf assumes it is unsigned int, 8 bytes, it prints extra FFFFFF82. To fix it, we can use format specifier...
70,245,354
70,247,443
deducing return type template c++
I'm making a parser combinator in c++. Currently, I'm trying to make a sequence function that will call other parsers in order and return all the results in a Tuple. Code template<typename T> T parse(std::function<T(Stream*)> parser, Stream* stream) { return parser(stream); } std::function<char(Stream*)> Char(char...
In C++11 you can figure out what std::functions R parameter is supposed to be in different places. I've chosen to make it a template parameter with a default type: template< typename... T, class R = decltype(std::make_tuple(std::declval<T>()(std::declval<Stream*>())...)) > auto Seq(T... a) -> std::function<R(St...
70,245,579
70,245,828
Problems with binary long handling
I made a binary decimal conversion menu which always take 0 for binary numbers #include<iostream> #include<cmath> using namespace std; int main() { int dec,ch,i; long bin,temp; do { dec=bin=i=ch=0; cout<<"\n\n\t\tMENU\n1. Deciml to Binary number\n2. Binary to Decimal number\n3. Exi...
Main problem is that many newbies have wrong mindset when trying to solve this problem. They assume the have to recalculate directly from decimal to binary. They amuse that int type some some kind of magic aware of desired base. In this insane approach they are trying to calculate a value, which printed in decimal repr...
70,246,137
70,246,204
c++ login system fails when it s not the first element of stl vector
I m trying to create a login system but I encounter an issue at login. If it's the first person from the vector the login is successful otherwise the login is failed. Here is the code: #include<iostream> #include<fstream> #include<string> #include<vector> using std::string; using std::cin; using std::cout; using std::e...
Instead of else { return false; } You want to continue the loop. Your function fails because of a premature return.
70,246,174
70,246,484
How can we set the memory of array using cstring packgae functions in c++
i want to allocate a number to whole array using memset function of cstring class.bbut it only works for 0,if i provide any other value to the function memset it randomly assigns a large integer no to the memory of array. memset(arr,0,sizeof(arr)); for this it works fine each slot in array i assigned 0 value; but if i...
I think you want std::fill. std::memset is a primitive function. It sets bytes in memory, not values. The value 257 in binary is 0x0101. That shows you what happened: both bytes were set to 0x01. Since you want to set the value to 0x0001, it clearly is not possible to do so with std::memset, since it sets everything to...
70,246,289
70,246,554
typedefing a pointer recognized by C to an inner C++ class
I have a class that I want to share between C and C++, where C is only able to get it as a pointer. However because it is an inner class it cannot be forward-declared. Instead this is what our current code does in a common header file: #ifdef __cplusplus class Container { public: class Object { public: ...
First of all, type-aliasing pointers is usually a recipe for trouble. Don't do it. Second, the "inner" class is an overused concept, so my first reflex would be to consider whether it's really necessary. If it is necessary, you can define an opaque empty type and derive from it for some type safety: In a shared header:...
70,246,716
70,249,086
Getting C26xxx errors in my C++ Windows service code
I'm getting errors in my code. The code compiles, but I'd still like to get rid of the warnings. I've looked on stackoverflow and google and clicked on the warnings which take me to the microsoft.com page, explaining each, but I don't see concrete examples of how to get rid of them. Here's the C++ code and the warnings...
Those are not compiler warnings but a code analysis warnings (based on CppCoreGuidelines), which give hints on how to improve code to prevent common errors - like null pointer dereferences and out of bound reads/writes. Fixing them might require use of gsl library of tools : https://github.com/microsoft/GSL. //C26485 ...
70,246,891
70,247,240
How to initialize tm struct memebers in initializer list of a structure in C++ 98 standard
I'm trying to initialize ::tm struct's members in a structure using initializer list as shown below. But it's only possible in C++ stds > 98. How can I achieve the same in C++ 98? struct abc { abc () : time_struct_{0,0,0,0,0,0,0,0,0}, x(0) { } ::tm time_struct_ ; int x; };
As Daniel Langr mentioned time_struct_() does the job.
70,246,995
70,247,043
Are temporary variables released at the end of a statement?
I'm trying to find out when temporary variables are released. I wrote the code below. #include <stdio.h> class C { public: C() { printf("C O\n"); } C(const C&) { printf("C& O\n"); } virtual ~C() { printf("C D\n"); } }; int kkk(const C&) { printf("kkk\n")...
From Temporary_object_lifetime All temporary objects are destroyed as the last step in evaluating the full-expression that (lexically) contains the point where they were created, and if multiple temporary objects were created, they are destroyed in the order opposite to the order of creation. This is true even if that...
70,247,123
70,249,302
Is there an simd/avx instruction to return a u8 mask for every 32 bit lane that isn't 0
Say i have a 256 bit wide vector like this: 00000000 00000000 11100110 00000000 00000000 00000000 00000000 00000000 00000000 00000000 10000101 00000000 00000000 00000000 01111110 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00001100 00000000 00000000 00000000 000000...
Assuming signed integer lanes: inline uint8_t positiveMask_epi32( __m256i vec ) { // Compare 32-bit integers for i > 0 const __m256i zero = _mm256_cmpgt_epi32( vec, _mm256_setzero_si256() ); // Collect high bits const int mask = _mm256_movemask_ps( _mm256_castsi256_ps( zero ) ); // Return that value...
70,247,395
70,247,479
Ambiguous overload for ‘operator=’ when trying to invoke the move assignment operator
I am trying to clarify-understand move semantics and, for that, I wrote the following code. I used a raw pointer as a data member only to practice in finding all the dangerous spots and also apply idioms like copy & swap. #include <iostream> #include <utility> class Example { protected: int* intPtr; public: Exa...
Example& operator=(Example anExample) is a general assignment operator. It copies lvalues and moves rvalues. If you want to distinguish copy from move assignment you need Example& operator=(const Example & anExample). Alternatively you could remove Example& operator=(Example&& anExample).
70,247,498
70,249,307
Reduce big O notation for faster runtime, now it doesnt execute because it is too long, anyone know a solution?
The code below is to calculate the exponential growth of fish. How can I reduce this to O(N) for a capable runtime? Now my code is O(N2) and it wont execute because it will take too long. Any suggestions? #include <fstream> #include <vector> #include <sstream> #include <numeric> void CalculateNewFish(std::vector <int...
Given that the number of fish grows exponentially, it is a bad idea to do a simulation that grows in space with the number of fish. We can avoid this by recognizing all fish with the same number of days remaining are identical and that there are only nine possible values, [0, ... , 8], of days remaining for a given fis...
70,247,818
70,248,965
What is lldb's equivalent one of gdb's advance command?
When debugging C/C++ function that with many arguments, and each arguments may still call some functions, people have to repeated typing step and finish, then reach where this function's body part. e.g. I'm using OpenCV's solvePnP() function, it requires many arguments: solvePnP(v_point_3d,v_point_2d,K,D,R,T); Amo...
Checkout the sif command for lldb. sif means **Step Into Function Reference: How to step-into outermost function call in the line with LLDB? To get all the supported commands of LLDB, one should first go into lldb command, then type help, then there will be the explanations for sif: sif -- Step through the curre...
70,247,908
70,247,988
Standard Ways Of Passing Array of Arrays To Other Functions in C++ Failing
I am attempting to pass a 2D array of integers from my main function in a cpp program to another function, and to manipulate the 2D array in this other function. While I've done this before, it's been a while, so I was following this accepted answer: Direct link to answer in question the below program is modeled direct...
An array when used in an expression decays to a pointer to its first element. So a variable of type int [LINES_IN_FILE][NUMS_PER_LINE] decays to type int (*)[NUMS_PER_LINE], and the latter in a function declaration can also be expressed as int [][NUMS_PER_LINE] So you want to use this function: void change2dArrayMethod...
70,248,058
70,248,416
why does using cin function give me error?
so i'm pretty new at coding and was solving a problem that i found in the book. Here's the code- #include <iostream> #include <string> using namespace std; void hours(double hours, string subs) { if (hours > 12 || subs != "AM" || "PM") { int tries = 0; while (tries <= 50) ; { ...
There were many errors (see the comments above). I've fixed it for you, compare to your original code #include <iostream> #include <string> using namespace std; double calculate_hours(double hours, string subs) { if( hours <= 0 || hours > 12 || ( subs != "AM" && subs != "PM")){ cout << "please check your i...
70,248,223
70,248,306
How can I make my function only accept odd numbers into my array, and reject even numbers? C++
Let me preface this by saying I am fairly new to functions and arrays. I have to make 3 functions: Function1 will be user input, Function2 will determine even/odd numbers, and Function3 will display the contents. I have Function1 and Function3 complete, and will post below, but I'm having a difficult time with Function...
for (int i = 0; i < size; i++) increments i each time through the loop. if (num[i] % 2 != 0) { i++; } increments i each time the number is odd. So each time the user inputs an odd number, i gets incremented twice. Change the loop control to for (int i = 0; i < size; } so that i only gets incremented on valid inp...
70,248,510
70,249,317
How do I load a bitmap into a Win32 application?
I am trying to load a bitmap in a Win32 application, but for some strange reason the bitmap does not load. Here is what I have so far: HANDLE hImg = LoadImageW( NULL, L"img.bmp", IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE ); if (hImg == NULL) { std::cout << GetLastError(); } Compiled on GCC 8.1.0 ...
You just need to change the window procedure to do all the drawing in WM_PAINT. Once the image is loaded successfully, create a memory DC, select the bitmap into the memory DC, and draw the memory DC onto the target window DC. When the bitmap handle from LoadImage is no longer needed, it should be deleted DeleteObject ...
70,248,658
70,249,141
Perspective projection turns cube into weird tv shaped cuboid
This is my perspective projection matrix code inline m4 Projection(float WidthOverHeight, float FOV) { float Near = 1.0f; float Far = 100.0f; float f = 1.0f/(float)tan(DegToRad(FOV / 2.0f)); float fn = 1.0f / (Near - Far); float a = f / WidthOverHeight; float b = f; float c = Far * fn; ...
OpenGL matrixes are stored with column major order. You have to read the columns from left to right. For example the 1st column of the matrix R is { c, 0, s, 0}, the 2nd one is { 0, 1, 0, 0} the 3rd is {-s, 0, c, 0} and the 4th is { 0, 0, 0, 1}. The lines in your code are actually columns (not rows). Therefore you need...
70,248,902
70,248,928
Fraction pattern in c++
I need to write a program to run this pattern in c++: S=1/2+2/3+3/4+4/5+...+N-1/N I have tried but my code is showing 0. And its the code that I have written: #include <iostream> using namespace std; int main() { unsigned int N; float S=0; cout << "Enter N:"; cin >> N; for (int I = 2; I <= N;...
(I - 1) / I only contains integers, therefore any remainder is discarded. You can avoid this by simply subtracting - 1.f off of I instead.
70,249,058
70,249,332
why for loop is not work correctly for a simple multiplication numbers 1 to 50?
code: #include <iostream> using namespace std; int main() { int answer = 1; int i = 1; for (; i <= 50; i++){ answer = answer * i; } cout << answer << endl; return 0; } resault : 0 ...Program finished with exit code 0 Press ENTER to exit console. when i run this code in an online c++ compiler, it ...
I will answer specifically the asked question "Why?" and not the one added in the comments "How?". You get the result 0 because one of the intermediate values of answer is 0 and multiplying anything with it will stay 0. Here are the intermediate values (I found them by moving your output into the loop.): 1 2 6 24 120 7...
70,249,073
70,249,163
How to seperate definition and implementation of a derived class constructor?
I would like to learn how to define a derived class constructor in one file so that I could implement it in another file. public: Derived(std::string name) : Base(name); ~Derived(); Destructor works as expected, however with constructor I either add {} at the end (instead of a semicolon) and then get redefinition of '...
Base.h #include <string> class Base { protected: std::string name; ... public: Base(std::string name); virtual ~Derived(); ... }; Base.cpp #include "Base.h" Base::Base(std::string name) : name(name) { ... } Base::~Base() { ... } Derived.h #include "Base.h" class Derived : public Ba...
70,249,647
70,252,123
The strong-ness of x86 store instruction wrt. SC-DRF?
I read about Herb's atomic<> Weapons talk and had a question about page 42: He mentioned that (50:00 in the video): (x86) stores are much stronger than they need to be... What I don't understand is: if the x86 "S" on the chart is a plain store, i.e. mov, I don't think it's stronger than SC-DRF because it's only a re...
Yes, he's showing xchg there (full barrier and an RMW operation), not just a mov store - a plain mov would be below the SC-DRF bar because it doesn't provide sequential consistency on its own without mfence or other barrier. Compare ARM64 stlr / ldar - they can't reorder with each other (not even StoreLoad), but stlr c...
70,249,721
70,249,867
type of input arguments depending on template boolean
My purpose is simple, data type of the input is depending on the template bool: template<bool isfloa> class example{ public: if (isfloa){ example(float p){printf("sizeof p: %d\n", sizeof(p))}; } else{ example(uint64_t p){printf("sizeof p: %d\n", sizeof(p))}; } }; This cannot pass the compliation and I ha...
You can use std::conditional template<bool isfloat> class example{ public: using value_type = std::conditional_t<isfloat,float,int>; example(value_type p){printf("sizeof p: %d\n", sizeof(p));} };
70,250,038
70,250,518
Can I somehow elegantly forbid using unsingned variables in my template function?
Consider this piece of code: template <typename T> T abs(const T& n) { if (!std::is_signed<T>::value) throw logic_error; if (n < 0) return -n; return n; } I want to completely forbid the usage of my function with unsigned variables, since it doesn't make sense, and probably the user doesn't...
1. concepts Since C++20 you can use concepts for this. If you are fine with integer only parameters you could use std::signed_integral: #include <concepts> template <std::signed_integral T> T abs(const T& n) { if (n < 0) return -n; return n; } If you want to also allow double, etc... you'd have to mak...
70,250,524
70,251,009
C++ class template taking either type or non-type
I see a few similar questions, but they don't seem to get at this. I can overload a function on a template: template <typename T> void foo(); // Called as e.g., foo<int>(); template <std::size_t I> void foo(); // Called as e.g., foo<2>(); Is there a way to do something similar with a class, where I can have either MyC...
You could specialize the class using the helper type std::integral_constant<int,N>. Though unfortunately this doesn't exactly allow the MyClass<2> syntax: #include <type_traits> template<typename T> class MyClass { }; template<int N> using ic = std::integral_constant<int,N>; template<int N> class MyClass<ic<N>> { }...
70,250,551
70,262,613
failure to compile imgui, glfw, opengl on linux with gcc 11.2
I've recently started coding with c++ and the project that im currently on requires imgui. so i set up the .h and .cpp libraries in a folder called "include" in the same folder as the source code. I'm currently trying to run the cpp in https://github.com/ocornut/imgui/tree/master/examples/example_glfw_opengl3 and compi...
Assuming you downloaded imgui to a place called $IMGUI_DIR and the file that contains your main function is main.cpp, your compile commandline should look like the following: (the \ are just there to break up the command) g++ main.cpp -o main \ $IMGUI_DIR/imgui*.cpp $IMGUI_DIR/backends/imgui_impl_glfw.cpp $IMGUI_DIR/ba...
70,251,054
70,251,112
c++ why do i get errors when using ternary operator
So here's my code, and I just can't find what's wrong. I would very much appreciate any help! #include <iostream> using namespace std; int main() { int x,I=2; for (x = 100 ; x <= 500; x++) { (x % 3 == 0 && x % 5 == 0)? (cout << x << endl) : (I = 2); } return 0; } errors: Update: I know...
The ternary operator is not an if-else. It's for doing something like this: int i = (3 < 4) ? 3 : 4; Please use if-else for this usage.
70,251,105
70,261,539
Get each row of an arma::mat matrix as arma::vec in for loop
I am using RcppArmadillo to create a function using stochastic simulation. I have trouble pulling out each row of a arma::mat as an arma::vec. Below is a simplified example of my problem. I have used R nomenclature to illustrate what I am trying to achieve. I believe there should be a fairly simple way of achieving thi...
Here is a simple (and very pedestrian, going step by step in the loop) answer for you. Code #include <RcppArmadillo.h> // [[Rcpp::depends(RcppArmadillo)]] // [[Rcpp::export]] arma::mat rowwiseAdd(arma::mat A, arma::mat B) { if (A.n_rows != B.n_rows || A.n_cols != B.n_cols) Rcpp::stop("Matrices must confor...
70,251,557
70,273,012
How to mock a vector of an arbitrary size?
I've defined a class that accepts a vector as a constructor input parameter and provides a method that uses vector's size() function: class Foo { vector<int> storedVector; public: explicit Foo(vector<int>); bool isSizeGreaterThanInt(); } Foo::Foo(vector<int> inputVector) : storedVector(std::move(inputVect...
You cannot mock methods of std::vector, because mocking system in GoogleTest is based on polymorphism and std::vector is not prepared for use in polymorphism - none of its methods are virtual. Since size() method is not virtual, the mock implementation will never be called and GoogleMock cannot register that call or ex...
70,251,722
70,251,855
Does not name a type C++
I am making a program that hopefully removes tags from html files. But when I am copiling the program I get the following error message : tag_remover.cc:11:1: error: ‘TagRemover’ does not name a type 11 | TagRemover::TagRemover(std::istream& in) { | ^~~~~~~~~~ tag_remover.cc:21:14: error: ‘TagRemover’ has not ...
First thing I notice: #include <iterator> Is nowhere to be found. It should be in tag_remover.cc std::istream_iterator<> Is defined in… <iterator> Also the TagRemover default constructor seems to be declared but not defined. Furthermore, you can define TagRemover::TagRemover(std::istream&) like this: TagRemover::TagR...
70,252,406
70,252,475
Why am I getting values that are outside of my rand function parameters?
I am trying to output 25 random values between 3 and 7 using a function. Every time I run my program, I receive two values that are within those parameters, but the rest are out of range. #include <iostream> #include <iomanip> using namespace std; void showArray(int a[], int size); void showArray(int a[], const int s...
You are calling rand() only 1 time, and storing the result in randomNumb, which is a single integer. Your array is being created with only 1 element in it - the value of randomNumb. But, you are telling showArray() that the array has 25 elements, which it doesn't. So, showArray() is going out of bounds of the array a...
70,252,660
70,254,426
C++: Initialize a variable of a specific type, logic. Consise way of approaching these problems
I have this problem generally, but my specific example is: When dealing with .wav data,for 16 bit waves, one uses a signed integer, whereas the 8 bit waves are unsigned. I would like to do something like the following: if (bytesPerSample == 2){ int16_t* buffer = new int16_t[1]; } else if (bytesPerSample == 1){ ...
C++17's std::variant type can hold multiple data types in the same space. You can then use std::visit to dispatch based on the type inside. If you combine this with templates, you only have to write one version of each function that processes the variable. template <typename T> void processSamples(const std::vector<T>&...
70,253,485
70,253,545
Is the main purpose of object serialization in C++ for faster object loading?
I am reading code for a project written by others. The main task of the project is to read contents from a large structured text file (.txt) with 8 columns into a KnowledgeBase object, which have a number of methods and variables. The KnowledgeBase object is then output into a binary file. For example, the KnowledgeBa...
Is the main purpose of object serialization in C++ for faster object loading? No. The most important purpose of serialisation is to transform the state of the program into a format that can be stored on the filesystem, or that can be communicated across a network, and that can be de-serialised back. Often, the purpos...
70,253,537
70,253,637
GLUT - Undefined reference to pressedButton(int, int)
I have a main method that contains the glutMotionFunc that receives the function movimentoMouseBotaoApertado that the signature is void movimentoMouseBotaoApertado(int, int). I have a .h and .cpp file, but when I import the .h at the main file and try to execute the code, the error appears undefined reference to movime...
I clicked with the right button and selected Add files recursively... and I chose the folders/files and worked it.
70,253,925
70,257,171
std::accumulate vs for loop, raytracing application
This question is based on this video on YouTube made with the purpose of reviewing this project. In the video, the host is analyzing the project and found out that the following block of code is a cause of performance issues: std::optional<HitRecord> HittableObjectList::Hit(const Ray &r, float t_min, float t_max) const...
Desclaimer: I did not run advanced tests, this is just my analysis based on the video and the code. From what I see in the profiling in the video, the hotspot in accumulate is here: _Val = _Reduce_op(_Val, *_UFirst); Since _Reduce_op is just our lambda, and the profiling shows this lambda is not the bottleneck, then i...
70,253,960
70,254,028
How can I access the define macro in the header file from other files with Conditional Compilation?
I have a macro in a header file: header.h #ifndef HEADER_H #define HEADER_H #define vulkan #endif I want to use this macro with #ifdef from other headers and sources files. game.h #ifndef GAME_H #define GAME_H #include "header.h" #ifdef vulkan //use vulkan api #else //use opengl api #endif #endif I also want to ...
i also want to use #ifdef in game.cpp source ... What is right way ? This is a right way: // game.cpp #include "header.h" If "header.h" defines a macro, then including it will bring the macro definition to the translation unit.
70,254,325
70,254,469
C++ dynamic linking to libraries upgrade
I have a question regarding dynamic linking libraries. Say I have a libfoo.so that requires libbar.so. Currently it links with libbar.so.100 (version 1.0.0). There's a new version of bar, libbar.so.200, and foo does not use any new features of bar v2.0.0. and APIs which it was using are unchanged. Can I straightaway up...
This is a question of ABI stability. Often "major" versions of libraries break ABI stability and it won't work. That is one common way to distinguish between major and minor version bumps; minor version bumps are backwards compatible, major ones are not. There is no guarantee at all either way. Many minor details cou...
70,254,822
70,254,986
passing vector of pointers
I'm having a problem with my vector passed in a function as a parameter. I'm getting the following error: void checkout(std::vector<InvoiceItem,std::allocator<InvoiceItem>>)': cannot convert argument 1 from 'std::vector<InvoiceItem *,std::allocator<InvoiceItem *>>' to 'std::vector<InvoiceItem,std::allocator<InvoiceItem...
I've distilled your question down to a minimum reproducible example. If you were to remove all unnecessary junk from your program, you would have something like this: #include <vector> using std::vector; class InvoiceItem {}; // (A) void checkout(vector<InvoiceItem> order); int main() { vector<InvoiceItem*> or...
70,255,312
70,255,344
When printing X variable it prints "123" then the actual variable value
When you type in 4 it should output only 2 but instead it outputs 12, same goes for 6 it outputs 123 and so on and so forth int main() { int salary, yearsOfService, X; //rounded off for computation of bonuse string companyName; std::cin >> yearsOfService; if (yearsOfService >= 1){ //X is round...
Your program is doing exactly what you told it to do. It will run down and execute those statements in sequence. It sounds like what you're trying to do is this: X = 0; if (yearsOfService >= 11) X = 5; else if (yearsOfService >= 6) X = 4; else if (yearsOfService >= 5) X = 3; else if (yearsOfService >= 2) ...
70,255,549
70,255,645
return std::move a class with a unique_ptr member
Why can't I return a class containing a std::unique_ptr, using std::move semantics (I thought), as in the example below? I thought that the return would invoke the move ctor of class A, which would std::move the std::unique_ptr. (I'm using gcc 11.2, C++20) Example: #include <memory> class A { public: explicit A(...
I thought that the return would invoke the move ctor of class A, which would std::move the std::unique_ptr. All true, but the move constructor only moves the members of A. It cannot move unrelated satellite unique pointers for you. In the expression A(m), you use m as an lvalue. That will try to copy m in order to in...
70,255,833
70,255,882
Two different enums have same items not working in c++
I really want to be able to do this in my code, but this error: redefinition of enumerator 'TEST' enum test1 { TEST }; enum test2 { TEST }; Is there a way to get around this since I really want the same names inside the different enums. Also why is this happening?
This can be solved by defining your enums as enum class instead of plain enums. By defining as a plain enum, the names are unscoped and therefore conflict with each other. If they are defined as enum classes, the names are contained within the scope of the enum. Note, however, that as a result of this change, you will ...
70,255,986
70,263,509
I need UTF8 encoded representation of a hex string, not UTF16
I need to get UTF8 representation of the following hex value, not UTF16. I am using C++ builder 11 setlocale(LC_ALL, ".UTF8"); String tb64 = UTF8String(U"D985");//Hex value of the letter م or M in arabic std::wstring hex; for(int i =1; i < tb64.Length()+1; ++i) hex += tb64[i]; int len = hex.length(); std::ws...
You are assigning the hex string to a UTF8String, and then assigning that to a (Unicode)String, which will convert the UTF-8 to UTF-16. Then you are creating a separate std::wstring from the UTF-16 characters. std::wstring uses UTF-16 on Windows and UTF-32 on other platforms. All of those string conversions are unneces...
70,256,871
70,330,454
In C++, how to detect that file has been already opened by own process?
I need to create a logger facility that outputs from different places of code to the same or different files depending on what the user provides. It should recreate a file for logging if it is not opened. But it must append to an already opened file. This naive way such as std::ofstream f1(“log”); f1 << "1 from f1\n"; ...
So here is a simple Linux specific code that checks whether a specified target file is open by the current process (using --std=c++17 for dir listing but any way can be used of course). #include <string> #include <iostream> #include <filesystem> #include <sys/types.h> #include <unistd.h> #include <limits.h> bool is_o...
70,257,218
70,269,061
"Could Not Load SSL Library" error in C++Builder
This has already been discussed several times, but this time I'm here to ask you because it's the same case. First of all, the point of the problem is that when using the Get() function of TIdHTTP on an HTTPS web page, a message appears that the SSL library cannot be loaded. So I added TIdSSLIOHandlerSocketOpenSSL to T...
In comments, you mention that Indy's WhichFailedToLoad() function is reporting various ..._indy functions are missing in the OpenSSL DLLs. The fact that Indy is looking for those functions means you are using Indy v8 or v9, not v10. You can verify that by looking at the gsIdVersion global variable in the IdGlobal uni...
70,257,579
70,257,730
How to set inverval in milisecond between gif frames with Imagemagick++
Creating a Gif using ImageMagick 6.9.7.4. I convert a vector of QImage, to ImageMagick image type and create a gif using the static method. But resulted gif is so fast, how can set I an interval between frames, or make by gif some slow? std::vector<Magick::Image> listOfImages; for (QImage &image:m_listOfImages) { ...
Image img1( "100x100", "white" ); img1.pixelColor( 49, 49, "red" ); frames.push_back(img1); Image img2( "100x100", "red" ); img2.pixelColor( 49, 49, "white" ); frames.push_back(img2); img1.animationDelay(2000); img2.animationDelay(2000);*/ Magick::writeImages(frames.begin(), frames.end(), "f:\\2.gif"); Sure, you sh...
70,257,751
70,258,061
Move a file or folder to the RecycleBin/Trash (C++17)
I am trying to write function to move files to trash. For example when I use a file path with unicode and whitespace I cannot send it to the Recycle Bin. ...\Yönü Değiştir\Yönü Değiştir Sil.txt I found many examples on the forum. But I couldn't run it correctly. Where did I go wrong, Can you help me write the function...
I think your conversion between wstring and string has problem. Note that std::filesystem supports converting to both string and wstring so let's re-write your code a bit bool recycle_file_folder(std::wstring path) { std::wstring widestr = path + std::wstring(1, L'\0'); SHFILEOPSTRUCT fileOp; fileOp...
70,257,914
70,257,994
Clang generates strange output when dividing two integers
I have written the following very simple code which I am experimenting with in godbolt's compiler explorer: #include <cstdint> uint64_t func(uint64_t num, uint64_t den) { return num / den; } GCC produces the following output, which I would expect: func(unsigned long, unsigned long): mov rax, rdi ...
The assembly seems to be checking if either num or den is larger than 2**32 by shifting right by 32 bits and then checking whether the resulting number is 0. Depending on the decision, a 64-bit division (div rsi) or 32-bit division (div esi) is performed. Presumably this code is generated because the compiler writer th...
70,258,201
70,258,308
Inputs of a method depending on the template structure
template <typename Stru_> class templateClasse{ public: using stru = Stru_; static void method_0(int sk, int sl){ printf("class templateClass method_0 sk: %d sl: %d\n", sk, sl); } static void method_1(int a){ if (stru::isvec){ method_0(0, a); ...
Does this code choose the method_0 during compilation? No, the dispatch happens at run-time. You can use constexpr if (since C++17) to make the dispatch performed at compile-time. void method_1(int a){ if constexpr (stru::isvec){ method_0(0, a); } else{ method_0(a, 0); } } The code is successfully ...
70,258,239
70,259,030
LED blinking only when Serial Monitor is not open
I have a really simple code that is not behaving how I would expect it to. Here's the code: int i; void setup() { Serial.begin(9600); pinMode(13, OUTPUT); } void loop() { //digitalWrite(13, HIGH); i = random(1,5); Serial.println(i); digitalWrite(13, HIGH); delay(1000); digitalWrite(13, LOW); } With...
If you want to blink a LED, you need to add an extra delay when the LED is going from OFF to ON. Currently you have: LED ON -> wait -> LED OFF -> (instantly) LED ON -> wait etc So what you see is just the LED continuously ON, to make it work add another delay(1000) before digitalWrite(13, HIGH) for example: int i; ...
70,258,418
70,258,852
Why is a segmentation fault not recoverable?
Following a previous question of mine, most comments say "just don't, you are in a limbo state, you have to kill everything and start over". There is also a "safeish" workaround. What I fail to understand is why a segmentation fault is inherently nonrecoverable. The moment in which writing to protected memory is caught...
When exactly does segmentation fault happen (=when is SIGSEGV sent)? When you attempt to access memory you don’t have access to, such as accessing an array out of bounds or dereferencing an invalid pointer. The signal SIGSEGV is standardized but different OS might implement it differently. "Segmentation fault" is mai...
70,258,567
70,291,681
Old task from local ICPC "Computer Class"
There is a task on which I have been racking my brains for three days. The task is called Computer Class (not to be confused with other tasks from ICPC, there are many similarly named tasks). Problem conditions: There are n * m (arranged respectively in m rows and n desks in each row) desks and students. Each student f...
I decided to just first collect all even and then odd ones on the screen as an answer, and in those units of cases in which this did not work, I simply hardcode (there were only two of them: 3x3; 2x3). You can see the code above.
70,258,578
70,285,800
c++ interface throws "undefined reference to `vtable for 'interface'" error
I am building a sound generator program in Java and I am trying to port it to c++ I can easily do this in Java, but I am new to c++ In c++ I have an interface called iSamplePlayer and this is the iSample.h file: class ISamplePlayer { public: virtual double GetFrequency() virtual void SetFrequencyAtZer...
OK, I was a dummy. I forgot to add = 0; to the other functions in the interface. Everyone that is learning c++ and already knows java or c#, all functions that you intend to be abstract need to be virtual and end in = 0; These are called pure virtual functions. Learn from my mistake.
70,259,260
70,259,283
Difference between a `vector` created from the std `<vector>` library, and an `STL vector` created from: `<stl_vector.h>`
Why are there two different vector libraries in the STD library?   stl_vector.h   vector.h What's the difference between the two?
If you look into the file itself you will see /** @file bits/stl_vector.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{vector} */ Your code should not directly include stl_vector.h. It's an implementation detail of libstdc++ and could be ab...
70,259,749
70,259,892
How to replace a number in a file with its sum?
I'd like to write a program that gets an integer in a file, sums it with a input number and replace the previous integer in the file with the result of the sum. I thought the following code would work, but there's a 0 written in the file that remains 0, no matter the integer I input. What am I doing wrong? #include <io...
You can try reading and writing the input file separately as shown below: #include <iostream> #include <fstream> using namespace std; int main() { ifstream arq("file.txt"); int points=0, total_points=0; cin >> points; arq >> total_points; total_points += points; arq.close(); ofstream o...
70,259,909
70,260,674
partial class template argument deduction in C++
I have a templated class but only part of the template arguments can be deduced from the constructor. Is there a way to provide the rest of the template arguments inside angle brackets when calling the constructor? Assume we're using C++17. template<typename T1, typename T2> struct S { T2 t2; S(const T2& _t2) ...
As mentioned in a comment, you can use a nested class such that the two parameters can be provided seperately (one explicitly the other deduced): template<typename T1> struct S { template <typename T2> struct impl { T2 t2; impl(const T2& _t2) : t2{_t2} {} }; template <typename T2> ...
70,260,994
70,261,259
Automatic template deduction C++20 with aggregate type
I am puzzled about this C++ code: template <class T> struct Foo { T value; }; int main() { return Foo<int>(0).value; // Below code works as well in gcc // return Foo(0).value; } It compiles with GCC 10 in C++20 standard (but not in C++17 standard) and latest MSVC, but not with clang 13 or 14, even in C...
It compiles with GCC 10 in C++20 standard (but not in C++17 standard) and latest MSVC. This is because GCC 10 and the latest MSVC implement allow initializing aggregates from a parenthesized list of values, which allows us to use parentheses to initialize aggregates. Also (this is strange), GCC in C++20 mode even co...
70,261,289
70,261,355
How to get the total 'percentage' of RAM in C++?
Hi I am building an application in C++. I want get the percentage of RAM that a windows machine is using. I tried a few codes like: string getRamUsage() { MEMORYSTATUSEX memInfo; memInfo.dwLength = sizeof(MEMORYSTATUSEX); DWORDLONG physMemUsed = memInfo.ullTotalPhys - memInfo.ullAvailPhys; return to_st...
You need to call GlobalMemoryStatusEx to get the data. MEMORYSTATUSEX statex; statex.dwLength = sizeof (statex); GlobalMemoryStatusEx (&statex); // it already contains the percentage auto memory_load = statex.dwMemoryLoad; // or calculate it from other field if need more digits. auto memory_load = 1 - (double)statex...
70,261,320
70,261,442
Visual Studio, How to SEPARATE the input and the output IN C++ Competitive Programming
I want to separate the input and the output this is MY CONSOLE and I want Like this WANTED OR in seperate files
You can store your answers in a container (vector, array, etc) and print all of them when no new inputs are expected. Keep in mind that in competitive programming, most of the times the judge doesn't care when you produce your output, unless specifically said so.
70,261,360
70,261,751
Warn against missing std:: prefixes due to ADL
It is possible to omit the std:: namespace for <algorithm>s when the argument types are in that namespace, which is usually the case. Is there any warning or clang-tidy rule that finds such omissions? #include <vector> #include <algorithm> std::vector<int> v; for_each(v.begin(), v.end(), [](auto){}); return 0; The ab...
There is an open change in tidy that could be used to flag this: D72282 - [clang-tidy] Add bugprone-unintended-adl [patch] Summary This patch adds bugprone-unintended-adl which flags uses of ADL that are not on the provided whitelist. bugprone-unintended-adl Finds usages of ADL (argument-dependent lookup), or potent...
70,261,395
70,263,071
Environment variable error while trying to create a solver in OpenFOAM 9
I'm trying to create a solver in my /opt/OpenFOAM/OpenFOAM-9/applications/solvers/electromagnetics directory using sudo foamNewSource App newSolver. But, I keep getting the following error: foamNewSource: Creating new interface file newSolver.C wmakeFilesAndOptions error: environment variable $WM_OPTIONS not set And t...
Using sudo in this case is not a good idea, instead run the scripts on your home directory: mkdir -p $FOAM_RUN cd $FOAM_RUN foamNewSource App newSolver For WM_OPTIONS environment variable, don't set it manually, instead use: export WM_OPTIONS=$WM_ARCH$WM_COMPILER$WM_PRECISION_OPTION$WM_LABEL_OPTION$WM_COMPILE_OPTION ...
70,261,453
70,261,840
Unable to use initializer list to assign values if structure contains a constructor
I was using initializer list to create object and assign it to the map with int key. In case of a simple structure the temporary structure can be created using initializer list. hence me doing something like this is totally valid struct fileJobPair { int file; int job; }; map<int, fileJobPair> mp; mp[1...
When you make a new fileJobPair, it will use by default your empty constructor, so will not be available anymore to be completed with {}. But you can add a new constructor to it, that receive 2 integers and bind them to the respective values, like this: #include <iostream> #include <map> using namespace std; struct f...
70,261,664
70,262,481
Can atomic read operations lead to deadlocks?
I am watching this Herb Sutter's talk about atomics, mutexes and memory barriers, and I have a question regarding it. Since 47:33 Herb explains how mutexes and atomics are related to memory ordering. On 49:12 he says, that with the default memory order, which is memory_order_seq_cst, atomic load() operation is equivale...
There's a misunderstanding here. An atomic read, regardless of memory order, is not "equivalent to locking a mutex". In terms of visibility it might have the same effects, but a mutex is much heavier. Here's a typical problem with a mutex: std::mutex mtx1; std::mutex mtx2; void thr1() { mtx1.lock(); mtx2.lock(...
70,261,859
70,262,077
Is my inheritance the same as the problematic "diamond inheritance"
I have multiple virtual base classes that create interfaces for my implementation classes. I however want them all to be able to serialize and deserialize themselves. This resultes in the following ABC inheritance: Lets say I have class A which allows for serialisation and deserialisation of the class. class A{ virtu...
What makes diamond inheritance "problematic" is that programmers new to C++ haven't yet learned about virtual inheritance and thus don't know how to achieve the diamond. Your inheritance is what people attempting the diamond inheritance end up with when they don't know how to make the diamond. However, what your inheri...
70,262,414
70,262,474
C++ multiple inheritance problem using FLTK
i've a problem drawing basic shape with fltk. I've made 2 classes'Rectangle' and 'Circle' that show normally. Then i've created a third class that inherit from 'Rectangle' and 'Circle' called 'RectangleAndCircle' : //declaration in BasicShape.h class Rectangle: public virtual BasicShape, public virtual Sketchable{ ...
You're using virtual inheritance. This means there will be only one instance of BasicShape in RectangleAndCircle. This BasicShape will have its fillColor set by both the Rectangle and Circle constructors, whichever being called last overwriting the value. My advice would be to not inherit here, and instead have two fie...
70,262,443
70,262,485
How to switch from vector::at() to [] when building Release
I find vector::at() useful for alerting against out-of-bounds bugs while debugging, but it's painfully slow and unsuited for release code. Is there a known compiler flag or some method to automatically convert vector::at() to vector::operator[] when compiling in release mode, sort of like how asserts() are stripped in ...
If you want no bounds checking overhead at runtime, then use the subscript operator. With most standard library implementations, you can enable non-standard bounds checking in subscript operator. Usually by defining a macro. This has a caveat, that the entire program must be compiled in the same mode, including any lin...
70,262,627
70,288,852
Is it safe to bind to C++ subobject's property in QML?
C++: database c++ object is exposed to QML as a context property. database c++ object has a method getDbpointObject() that returns pointer to databasePoint C++ object. databasePoint C++ object has a property named cppProp. main.cpp: // expose database object to qml database databaseObj; engine.rootContext()->setContext...
Response from Qt Support: In binding.qml, QML property bindProp is binded to myQmlComp.qmlCompProp.cppProp Is this binding safe? Looks like. Will the binding always be resolved? Assuming no reference issues, yes databasePoint c++ object is assigned to qmlCompProp in Component.onCompleted. Until then, qmlCompProp is...
70,262,742
70,262,821
How do I use std::rename with variables?
In my program, I store data in different text files. The data belongs to an object, which I call rockets. For example, the rocket Saturn 5 has a text file labeled "Saturn5R.txt". I want an option to rename the rocket, and so I will need to rename the text file as well. I am using std::rename in the library. I have got...
This has little to do with std::rename, and everything to do with how to interpolate variables into a string. A simple solution is to use std::string. It has overloaded operator + that can be used to concatenate substrings. If you want to make the program a bit fancier, C++20 added std::format: std::string oldname = s...
70,263,094
70,263,306
How to implement parts of member functions of a Class in a static library while the rest functions implemented in a cpp file?
I have a C++ Class A like this: // in header file A.h class A { public: void foo1(); void foo2(); private: double m_a; }; // in cpp file A1.cpp void A::foo1(){ m_a = 0; //do something with m_a } // in cpp file A2.cpp void A::foo2(){ foo1(); // call foo1 } // in cpp file main.cpp int main(){ ...
You can compile A1.cpp without linking, which will give you a compiled object file, A1.o. You can hand this off, so the developers for A2.cpp won't be able to see the source, but will be able to link your object file to build the final project. With g++, that could look like: A.h class A { public: void foo1(); ...
70,263,143
70,263,224
Unexpected default constructor call when using move semantics
I have two similar pieces of code. The first version unexpectedly calls the default constructor while the second doesn't. They both call the move operator / move constructor, respectively, as expected. class MyResource { public: MyResource() : m_data(0) { std::cout << "Default Ctor" << std::endl; } MyResource(i...
Members are initialized before the construct body runs. A much simpler example to see the same: #include <iostream> struct foo { foo(int) { std::cout << "ctr\n";} foo() { std::cout << "default ctr\n";} void operator=(const foo&) { std::cout << "assignment\n"; } }; struct bar { foo f; bar(int) : f(...
70,263,212
70,264,443
How do I input random numbers in C++ array?
#include <iostream> #include <ctime> using namespace std; int randBetween() { unsigned seed = time(0); srand(seed); const int MIN_VALUE = -100; const int MAX_VALUE = 100; return (rand() % (MAX_VALUE - MIN_VALUE + 1 )) + MIN_VALUE; } int main() { const int SIZE = 10; ...
First we'll take a look at your code and critique it. #include <iostream> #include <ctime> // MISSING <cstdlib> for C random functions using namespace std; // Bad Practice int randBetween() { unsigned seed = time(0); // Wrong placement; should only instantiate ONCE srand(seed); const int MIN_VA...
70,263,658
70,403,129
Lambda in return statement cannot be implicitly converted to functor
I have the following code struct Functor { Functor(std::function<void()> task) : _task {task} {} void operator() () {_task();} std::function<void()> _task{}; }; Functor run1() //OK { return Functor([](){std::cout << "From function" << std::endl;}); } Functor run2() //Bad. Compile time error { retu...
As it is already mentioned in the comments, run2 requires two implicit user conversions, which is prohibited. You can create a template constructor in Functor to make your code valid: #include <functional> #include <iostream> struct Functor { Functor(auto && task) : _task { task } {} void operator() () {_t...
70,263,686
70,263,929
How to load into __m256 from a float* but reading backwards in memory as opposed to forwards?
I've got an array of floats that I'd like to access in reverse order. In my non-vectorized code this is easy. Here is a simplifed version of the data that I have. float A[8] = {a, b, c, d, e, f, g, h}; float B[8] = {s, t, u, v, w, x, y, z}; Here is the operation I would like to do. float C[8] = {a*z, b*y, c*x, d*w, e*...
You can reverse the order inside a __m256 in two steps, using _mm256_permute_ps and _mm_256_permute2f128_ps. _mm256_permute_ps allows you to permute within each "lane", the high and low 128-bit chunks. _mm_256_permute2f128_ps allows you to permute 128-bit chunks across lanes. It's something like this: __m256 b = _m...
70,263,892
70,285,486
How to compile C++ app for Windows XP in MSVS?
As I read this article, it is enough to download most recent MSVS 2022 and then install toolset C++ Windows XP Support for VS 2017 (v141) tools [Deprecated]. After that in Visual Studio inside project properties I set this toolset. According to linked article it is enough to compile C++ app with XP support. But after m...
TL;DR For Window XP VC++ REDIST support, install https://aka.ms/vs/15/release/VC_redist.x86.exe on your Windows XP system -or- if you are doing "side-by-side application local deployment", then use the DLLs from C:\Program Files\Microsoft Visual Studio\2022\<edition>\VC\Redist\MSVC\14.16.27012\x86\Microsoft.VC141.CRT....
70,263,965
70,264,043
Can C++ concepts operate on overload sets?
C++ has an obnoxious limitation that it is impossible to pass overloaded functions to templates, for example std::max can not be nicely used with std::transform. I was thinking that it would be nice if concepts could solve this, but in my attempts I hit the same issue. It looks like concepts are not able to constrain t...
In order for the language to consider whether a type fulfills a concept, C++ must first deduce the type of the argument and plug it into the template function. That deduction cannot happen because the argument is a name representing a function with multiple overloads. So concepts don't even get a chance to work. So lon...
70,263,985
70,264,048
Strange error in C++ without stoping the program
When I change the value that I pass to my array I receive strange error which doesn't stop the program but it always appears so I'm curious why. I give you my code below: My error is something like: In function 'int numOfDifferentElements(BSTree*, int)': control reaches end of non-void function [-Wreturn-type] ( main.c...
The problem is that in your numOfDifferentElements function, if the if condition is satisified then there is no return statement. The problem is because the return type of the function is non-void and so you must return something. You can solve this by adding a return statement inside the if block or outside(after) the...
70,264,034
70,264,528
How to create array of classes containing a constructor with reference argument?
I have the piece of code hereunder which gives me the following errors: test.cpp:15:38: error: could not convert ‘std::ref<boost::asio::io_context>(((container*)this)->container::ioCtxt)’ from ‘std::reference_wrapper<boost::asio::io_context>’ to ‘A’ 15 | std::array<A,2> bObjs = {std::ref(this->ioCtxt), nullptr};...
Conmpiler can't do implicit conversion via initializer list: #include <functional> #include <array> struct from{}; struct a { a(from&){} }; int main() { from arg{}; // std::array<a, 1> ar{std::ref(arg)}; // can't deduce from initializer list std::array<a, 1> ar{ arg }; // alright std::array<a, ...
70,264,324
70,278,417
Image Magick++ close .display() Popup window by command
in documentation of Magick++ I found the command to display an image Image temp_image(my_image);temp_image.display(); // display 'my_image' in a pop-up window this works quite well, but I can find a command to close this window by code. My goal is to open a window with the image, give image new name by commandline inp...
Magick++, and ImageMagick, doesn't have any methods to manage active display windows. You can roll your own XWindow method, but most projects I've seen just do the following routine... Write temporary image Ask OS to open temporary file by forking a process & calling xdg-open, open, or start commands (depending on OS)...
70,264,455
70,266,823
How do I make child processes in Win32 so that they show up as nested in Task Manager?
I have a Win32 C++ application. I'm trying to launch one or several child processes with CreateProcess. I want the children to close when the parent does. I achieved this by creating a job and enabling JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE: HANDLE hJob = CreateJobObject(NULL, NULL); JOBOBJECT_EXTENDED_LIMIT_INFORMATION e...
Exactly what Task manager is doing is not documented. In Windows 8 it does not group child processes, it only organizes based on a process having a window or by being "special". How does Task Manager categorize processes as App, Background Process, or Windows Process?: These are terms that Task Manager simply made up....
70,264,522
70,264,662
uninitialized local variable used c++
Why can't I initialize the integer variable num with the value of the number field of the Strct structure? #include <iostream> struct Strct { float number = 16.0f; }; int main() { Strct* strct; int num = strct->number; return 0; } Error List: C4700 uninitialized local variable 'strct' used
Why can't I initialize the integer variable num with the value of the number field of the Strct structure? Because the pointer is uninitialised, and thus it doesn't point to any object. Indirecting through the pointer, or even reading the value of the pointer result in undefined behaviour. I thought my strct points ...
70,264,696
70,272,004
Why is the data parsed by pugixml lost in another function?
I have 2 functions: void XMLParser::ParseScene(const char* path) { // Load the XML file pugi::xml_document doc; pugi::xml_parse_result result = doc.load_file(path); scene = doc.child("scene"); } and void XMLParser::CreateModelLights(pugi::xml_node node) { GLuint i = 0; for (pugi::xml_node enti...
This is not terribly clear in the documentation, but PugiXML uses a fairly common memory management pattern: The pugi::xml_document owns the entire XML DOM tree, and pugi::xml_node objects are just shallow pointers into this tree. This means that you need to keep the pugi::xml_document object alive for as long as there...
70,264,739
70,264,809
C++ printf("%s" , string) is giving me very strange output
I am trying to use printf to give my strings color with something like printf("\x1B[92m%d\033[0m", value1); which works for me with integers no problem, but when I try to do something like printf("\x1B[92m%s\033[0m", wantedString); I get random things like, (°√, any help pls? Here is the whole function void searchFil...
For printf you need a c-style string. Use wantedString.c_str().
70,264,942
70,265,295
_itoa_s doesn't accept dynamic array
I am new to C++ and dynamic memory allocation. I have this code to convert a number from decimal to hexadecimal, that uses a dynamic array: int hexLen = value.length(); char* arrayPtr = new char[hexLen]; _itoa_s(stoi(dec), arrayPtr, 16); string hexVal = static_cast<string>(arrayPtr); delete[] charArrayptr; When I u...
If you read the documentation carefully, you would see that you are trying to call the template overload of _itoa_s() that takes in a reference to a fixed-sized array: template <size_t size> errno_t _itoa_s( int value, char (&buffer)[size], int radix ); You would need to instead call the non-template overload that t...
70,265,092
70,272,131
Template argument deduction/substitution failed with Boost Hana type_c
I do not understand why the following simple example fails: #include <boost/hana.hpp> template <typename _T> static constexpr void Foo(boost::hana::type<_T>) { } int main() { Foo(boost::hana::type_c<int>); return 0; } I get the following error message: [build] error: no matching function for call to ‘Foo(boo...
type_c<int> is a variable template that creates a value of type type<int>. It indeed seems like Foo should easily deduce parameter _T from type<_T> when passing type<int>. However it is not possible because type is an alias template that refers to member of some auxiliary class and its parameter is always in non-deduc...