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,272,037
73,272,099
How do you find out the cause of rare crashes that are caused by things that are not caught by try catch (access violation, divide by zero, etc.)?
I am a .NET programmer who is starting to dabble into C++. In C# I would put the root function in a try catch, this way I would catch all exceptions, save the stack trace, and this way I would know what caused the exception, significantly reducing the time spent debugging. But in C++ some stuff(access violation, divide...
C++ is meant to be a high performance language and checks are expensive. You can't run at C++ speeds and at the same time have all sorts of checks. It is by design. Running .Net this way is akin to running C++ in debug mode with sanitizers on. So if you want to run your application with all the information you can, tur...
73,272,190
73,272,408
C++ convert iterator from map to object pointer
Trying to find an object in a map, and set a member class pointer variable. # Animations.h #ifndef _ANIMATIONS_H #define _ANIMATIONS_H #include <map> #include "Animation.h" using namespace std; class Animations { public: Animations(); void add(Animation* animation, string name); void play(string name);...
I switched to non pointers in the map # Animations.h map<string, Animation> animations; Animation* animation; while leaving the animation a pointer. Then thanks to @EtiennedMartel's comment I used &itr->second to set the Animation* animation pointer. The other thing I needed to do was to add a default Animation() con...
73,272,505
73,272,547
Discrepancy in C++ constructor destructor execution order
I understand that the order of calling the destructor is in the reverse order of creation of the objects. However in the following code I don't understand why the destructor for C(1) and C(2) get called immediately after their constructor. Also what is the difference between statements: C(2) and C c3(3). The second one...
C(1); is a statement containing an expression that creates a temporary of type C, constructed from the argument 1. The temporary is not named - there is no variable name, and no way to refer to that object after the statement finishes executing - so the temporary object's destructor runs immediately after the statemen...
73,272,889
73,273,317
Why visual c++ (latest) and gcc 12.1 accepted hiding this init capture for lambda, while clang 14.0.0 not? (c++20)
Case 1 int main() { int x = 100; auto lamb_var = [y = x](){ int y = 10; return y + 1; }; assert (lamb_var() == 11); return 0; } in https://godbolt.org/z/hPPParjnz Both MSVC and GCC accepted shadowing the init-capture, while Clang accused y redefinition on...
I think that clang is correct in rejecting snippet 1 and accepting snippet 2 because in the first case the non-static data member is named y while in the second case the non-static data member is unnamed. Case 1 Here we consider snippet 1: int main() { int x = 100; auto lamb_var = [y = x](){ //the data member ...
73,273,084
73,273,145
How to dynamically allocate work to threads
I am trying to write code for finding if pairwise sums are even or not(among all possible pairs from 0 to 100000). I have written code using pthreads where the work allocation is done statically. Here is the code #include<iostream> #include<chrono> #include<iomanip> #include<pthread.h> using namespace std; #define MA...
This is the classic usage of a thread pool. Typically you set up a synchronized queue that can be pushed and pulled by any number of threads. Then you start N threads, the "thread pool". These threads wait on a condition variable that locks a mutex. When you have work to do from the main thread, it pushes work into the...
73,273,305
73,273,609
why the text of label didn't show the result initialized in custom class?
There is the complete process: Create a project, choose Base class: QWidget, including .h .cpp .ui [Add New...] -> create a [ C++ class] -> choose base class: [QWidget], but named myLabel. Open mylabel.h, change QWidget of including file and parent class to QLabel mylabel.h #ifndef MYLABEL_H #define MYLABEL_H #incl...
Check the code of setupUi method. When you use QT Designer to create your widget, each widget has some properties (like geometry, object name, initial text for label etc) which have to be initialized. This is done in setupUi. The code corresponding your case may look like: void setupUi() { label = new myLabel...
73,273,696
73,273,846
Unable to read from external text file
I've got a dynamically allocated array of a struct type (let's call it structtype), and I was trying to read to it from an external text file. structtype looks something like this: { char itemName[15]; char status; int itemAmt; char tried; char desc[130]; int rating; } And the text file looks s...
Here's what your code should look like. I've ignored the AllItems and AllGames arrays, and just concentrated on temparray while (!file_in.eof() && i < 15){ // Checks if its the end of the file, or if its the max amount I can store file_in.getline(temparray[i].itemName, 15, ':'); file_in >> temparray...
73,273,817
73,274,047
How to erase a string if it contains any character in a set [c++]
I am new to C++ and could not find a solution in any post for this. I have a vector of strings and I wish to erase a string from this vector if it contains any of these symbols: {'.', '%', '&','(',')', '!', '-', '{', '}'}. I am aware of find(), which only takes one character to search for; however, I want to go through...
There are two issues in your code, both 'inside' the inner for loop when a match is found. First, you keep checking the same vector element for a (further) match, even after you erase it; to fix this, add a break; statement inside the if block, to prevent further runs of that inner loop after a match has been found and...
73,274,134
73,274,170
Why is the counter value not incrementing?
The counter does not increase at all so I want to know which part went wrong. #include <cstring> #include <iostream> using namespace std; int main(){ int total=0,na=0,ni=0;//use to count how much type of element is there string chem; getline(cin,chem); for(int i=0;i!='\0';i++){ if(che...
for(int i=0;i!='\0';i++){ is the same as for(int i=0; i; i++){ ('\0' is a char type with value 0). The conditional check means the loop body never runs.
73,274,152
73,274,360
Undefined reference while compiling (compiler flag problem)
I am working on a project where I use google protobuffers. I am currently stuck at the compilation of the program in the CLion IDE. Everytime I compile with WSL, the following errors occur: /usr/bin/ld: /mnt/c/Users/***/Documents/***/Protobuf_examples/data.pb.cc:146: undefined reference to `google::protobuf::internal::...
Thanks to the comment of "Some programmer dude" its clear that this is not a compiler issue but a linker issue. Therefore putting linker flags into the compiler flags results in it not operating. Thanks to DevSolar I made some more changes to the CMake and it now looks like this: cmake_minimum_required(VERSION 3.21) pr...
73,274,651
73,282,916
why dbghelp cannot resolve symbol from managed callstack?
What's the difference between managed callstack and native callstack, why cannot resolve the symbol from managed callstack by dbghelp? can anyone tell me the basic reason?
When a native exe runs, windows maps the exe (and dll's) into memory using memory mapped files functionality (not that that matters). So when your program runs, you have a module address which is the base address that the native exe (or dll) image is loaded from (e.g. module address points to the first byte in the exe...
73,275,059
73,275,100
Cannot run .exe file from VS Code Terminal / Powershell
In my folder are these files: hello.cpp hello.exe hello.ilk hello.pdb When I try to execute the .exe file within a terminal in VS Code I receive this: C:\Users\User\Documents\VS_Code> hello.exe hello.exe : The term 'hello.exe' is not recognized as the name of a cmdlet, function, script file, or operable program....
I think your issue can be solved by just looking at the error suggestion. It says to use .\hello.exe . Hope this helps :)
73,275,424
73,275,936
Is there any way to implicitly convert parameters in template functions
I'm using lazy_importer recently but I get a strange error when calling functions; for example: LI_FN(WriteFile)(DiskHandle, Sector, sizeof(Sector), &Bytes, NULL); I get this error: C2664,Cannot convert parameter 5 from '_Ty' to 'LPOVERLAPPED' The below code fixes this: LI_FN(WriteFile)(DiskHandle, Sector, sizeof(Se...
The issue occurs because of your use of the NULL token, which is basically a C language macro for a null pointer. Relevant cppreference page. Typically, for a C compilation, NULL is defined as a void* pointer with a value of zero, like this (the exact definition can vary between compilers and platforms, but the C Stand...
73,276,161
73,276,890
How to use `boost::dynamic_properties` with vector valued property maps?
I would like to include a map<string, vector<int>> in a boost::dynamic_properties property: #include <map> #include <string> #include <vector> #include <boost/property_map/dynamic_property_map.hpp> #include <boost/property_map/property_map.hpp> auto main() -> int { auto name2numbers = std::map<std::string, std::vec...
If you want to “hack” solution by providing operator<< for a standard library type, you need to declare it in one of the associated namespaces for argument dependent lookup. Specifically you would need to declare this overload inside namespace std (because both std::vector and std::o stream are declared there). However...
73,276,389
73,276,580
How to Store and retrieve the the correct Type of DerivedClass Pointer To/From Map of BaseClass Pointer
Hello i have question about Maps and Inheritance. I have Map of BaseClass Pointer: std::map<int,std::shared_ptr<Game>> GamesByID; and inserted Derived Class Pointer into it like: GamesByID.insert(make_pair(ID,std::make_shared<ActionGame>(ID,Title,Metacritic,Recommendations,Price,lvl))); now i wanted to count how many A...
The map contains pointers of type "Game" nothing to do with derived class, the name to store a derived class with a pointer of base class is called polymorphism, You will need a function to return something like a flag to get what type of class it is. What I'm trying to say is that polymorphism will let you create a po...
73,276,625
73,279,817
How to resolve "Make sure the web address //ieframe.dll/dnserrordiagoff.htm# is correct" error in wxWebView (wxWidgets)
I am using wxWebView for showing our page content and when I don't have any content for the page, i.e. page is blank, I see the following error: I have my own file system handler class derived from wxWebViewHandler like below and in GetFile function, I set the content of page. Everything works fine except when page do...
So the problem is when the page content is empty. So I just tried to add a space char to my memory input stream like below and see the effect. It seems working! Basically I replaced return new wxFSFile( new wxMemoryInputStream( "", 0 ), uri, wxT( "text/html" ), dst_->currentAnchor_ #if wxUSE_DATETIME ...
73,278,382
73,284,613
RocksDB: iterator upper bound not working as expected
I need to store a bunch of values in RocksDB (using v6.20.3) with the keys in the following format: PREFIX_<INTEGER_ID>. The INTEGER_ID is a running sequence of numbers from 0 to N. I use a serialize_uint32_t function which converts the integer IDs to lexographic ordered strings (since I need to iterate the integers in...
I'm not sure whether it is the root cause but the code has a bug. rocksdb::Slice is similar to std::string_view. It points to a char array but doesn't maintain it. After upper_bound is constructed, key_prefix + serialize_uint32_t(6) might get destroyed, so read_opts.iterate_upper_bound points to a destroyed memory. The...
73,279,043
73,279,108
How to use the same object instance when creating other objects?
I'm new to C++ and started playing with references, which led me to the following code: #include <iostream> #include <unordered_map> class Wrapper { private: std::unordered_map<std::string, int> map; public: void add(std::string &key, int value) { map[key] = value; } int get(std::string &key) { return map[...
member variable must also be declared as reference, in both reader and writer class Writer { private: Wrapper & wrapper; } class Reader { private: Wrapper & wrapper; }
73,279,395
73,282,533
How can I resize QTableView row according to specific cell value?
I want to resize the row height according to a specific column value. For example, the table I want to change is here: At row 10, row height is resized by the third column value. But at row 11 it is resized by the second column value. I want to resize row height by only the third column value. Is there a way to do thi...
I haven't actually tried it myself, but from looking at the Qt source code (in particular the source code for QTableView::rowHeight(int) const and QHeaderView::sectionSizeFromContents(int) const), it looks like you could do something like: const int addressColumnLogicalIndex = 1; // i.e. 2nd column in the table const ...
73,279,562
73,280,255
How to explicitly specify template arguments for multiple parameter packs
I am trying to understand the following code: template <class...Ts, class...Us> void f(void) {}; int main() { f<int, char, float, double>(); } I don't know how template argument deduction deduces Ts and Us. In this answer, I learned that parameter packs are greedy, so Ts will match all specified arguments: [ Ts = i...
Regarding the second part of the question (second example). Template argument deduction deduces parameter packs Ts as [int, char], and Us as [ float, double ] the same way it deduces T if you have the following: template <class> struct B {}; template <class T> void h(B<T>) .. and you call h(B<int>()), template argumen...
73,279,731
73,279,793
variadic arguments which are all a specialization of a template type
We can validate at compile time that an input to a function is a specialization of a template. I.E the following code validates that the input for f is some specialization of struct Holder. template<typename T> struct Holder<T> {...}; template<typename T> void f(Holder<T> h) {...}; I want to validate that a set of va...
You can store the args in a tuple and calculate the index of the last Holder argument, then extract the Holder and normal arguments by index and forward them to the corresponding function. #include <tuple> template<class T> constexpr bool is_holder = false; template<class T> constexpr bool is_holder<Holder<T>> = true;...
73,279,841
73,280,028
One liner template type changer
I'm sorry for the title, I don't know how to call it... I'm trying to make a one liner of the caller() function (C++20). template <typename T> void func() { std::cerr << typeid(T).name() << std::endl; } void caller(const int &_i) { switch(_i) { case 1: func<uint8_t>(); break; ...
If you can provide the value to caller at compile time, you can do something like this: template<std::size_t> struct int_type_id; template<> struct int_type_id<0> { using type = std::uint8_t; }; template<> struct int_type_id<1> { using type = std::uint16_t; }; template<> struct int_type_id<2> { using type = std::uin...
73,279,958
73,281,488
QString::replace doesnt replace
Problem I am trying to convert a string to a C string. In doing so, I need to replace " with \". I use the following code to do this: QString Converter::plain2C(const QString &in) { QString out; // Split input in each line QStringList list = in.split(QChar('\n')); for (int i = 0; list.length() > i; i++...
It works now. The problem was the line above: line.replace(QChar('\'), QLatin1String("\\\\")); // replace \ with \\ The problem was that the comment ended with 2 \. That somehow disabled the next line or something like that. Anyway, this is the working code: QString Converter::plain2C(const QString &in) { QStrin...
73,280,301
73,281,511
QT/C++ Call function of a widget using a slot
Consider following main.cpp (the only file of the whole Qt-project): #include <QApplication> #include <QWidget> #include <QPushButton> #include <QVBoxLayout> #include <QLabel> #include <QObject> #pragma once class collectedFunctions : public QObject { Q_OBJECT public: collectedFunctions(QObject* parent = 0) {...
you shouldn't use the Q_OBJECT macro in main.cpp. The Q_OBJECT macro must appear in the private section of a class definition that declares its own signals and slots or that uses other services provided by Qt's meta-object system. The moc tool reads a C++ header file. If it finds one or more class declarations that co...
73,280,363
73,280,478
Why is this code involving the ternary operator getting an error in C, but not in C++?
I get "error: lvalue required as left operand of assignment" for "x=k" in C, but the code runs without an error in C++. I don't understand why C is giving me this error, while C++ doesn't. #include <stdio.h> int main() { int j=10, k=50, x; j<k ? x=j : x=k; printf("%d",x); }
In C, the ternary operator ?: has higher precedence than the assignment operator =. So this: j<k ? x=j : x=k; Parses as this: ((j<k) ? (x=j) : x)=k; This is an error in C because the result of the ternary operator is not an lvalue, i.e. it does not denote an object and so can't appear on the left side of an assignme...
73,280,646
73,280,767
best strategy for ensuring no copies in return by value
I'm using c++17, but I don't get to choose my compiler. Suppose I have type S with move and copy semantics. Typically for me S will be a std::vector of some aggregate type. I'm also using a function g which returns an S by value: S g(int x); Suppose further I'm writing this function, f, with a single return statemen...
Use (i). (i) and (ii) are the same, both guarantee zero copies/moves since C++17. An extra constructor call in (ii) doesn't help at all, it's just one more thing to elide with the mandatory RVO. (iii) is worse: it guarantees a move at worst, or no move if the compiler performs NRVO (in which case it becomes the same as...
73,280,748
73,282,307
std::variant having for possible type a ptr to an array of a given type. Can I store more information that just type?
I am looking at using std::variant to store basic types such as float, int, float2, float2, bool2, bool4, etc. which is rather trivial, but I would also ideally like to construct variant objects holding a pointer to a typed array. I came up with this solution, which compiles and run without crashing (which doesn't mean...
This "pointer plus size" type already exists since C++20 and it's called std::span. You can use std::variant<float, float3, std::span<float3>> If you want an array of many different types, you could use std::variant<std::span<float3>, std::span<float2>, std::span<bool2>, etc>. Notice that you do have to write all the t...
73,280,786
73,314,596
DLL not found in redistributable (biddll.dll)
I’m having difficulty getting the sample code for tws api running. I’ve successfully run it on a borrowed laptop but the same version fails on my own windows 10 laptop. When running on Release mode in Win32, I get the popups The code execution cannot proceed because biddll.dll was not found. Reinstalling the program ma...
Thanks for your suggestions. I uninstalled TWS API and reinstalled it. I made sure to build for Release. It sounds like there was a mismatch between some debug libraries and it started pulling them instead. There may have been some unexpected behavior from installing several versions while troubleshooting as well.
73,281,227
73,434,784
How to instantiate templated functors F<D> over multiple functors F1,F2 and multiple template parameters D1,D2?
I need to instantiate a bunch of functors template<typename DataType> struct Functor1{ int a; Functor1(int a_){ a = a_; } // __device__ void operator()(DataType &elem) elem.x +=1; } }; template<typename DataType> struct Functor2{ int a; Functor2(int a_){ a = a_; } // __device__ void ...
I want a macros/metaprogrammic trick the code above Here is a way to do this using templates instead of macros. The below program works for arbitrary number of Functors and Ds. See the different instantiations at the end of this answer, for different combinations of Functors and Ds. template<template<typename>typenam...
73,282,147
73,290,794
Throwing exception in constructor before member initializer list?
As an example, say I have the class class A{ B& foo; }; and I want to initialize this class with a constructor that takes in a vector and an index (just for example). So I get explicit A(std::vector<B>& lst, int index): foo(lst[index]) {}; However, accessing a random index in the vector is unsafe,...
Besides the solutions in the comments, you can use the ternary operator: explicit A(std::vector<B>& lst, int index): foo(lst[index < lst.size() ? index : throw blah_blah()]) {} It requires no helper functions and allows customizing your throw.
73,282,337
73,282,784
Why is my C++ code with file output not working?
I didn't got any errors, but my C++ code is still not working. It's really simple: #include <fstream> #include <iostream> using namespace std; int main() { string a; ofstream fout("char.out"); ifstream fin("char.in"); fin >> a; fout << a; return 0; } char.in after running: uiui char.out ...
in fact for reading and writing you should open and close file but you didn't close. Also you have two files where you have done writing from one file and reading from another file, I wonder how you expect to get the correct output. this is how it should be : #include <fstream> #include <iostream> using namespace std;...
73,282,668
73,282,710
Using an initialized object from one .cpp in another .cpp file without classess
I'm trying to split some functionality between multiple .cpp files and I've got an issue. Let's say, I have: Extra.h #include "CustomClass.h" namespace extraSpace { extern int justInteger; extern CustomClass *complexObject; } Extra.cpp include "Extra.h" int extraSpace::justInteger = 1; CustomClass *ext...
CustomClass *extraSpace::complexObject = new CustomClass; complexObject->SomeProperty = 1; // Can't do this You can use a lamda. CustomClass *extraSpace::complexObject = [] { auto* complexObject = new CustomClass; complexObject->SomeProperty = 1; return complexObject; }();
73,282,921
73,283,549
Find when a particular place in memory is changed in c++
Let's say I have an object MyObject and it has an attribute double MyObject::a. When I initialize a I set it to 0.05, but at some point when I run my code I notice that a is 1.something e-316, even though my code is never supposed to change its value. If I knew an exact place in memory that a occupies, is there a tool ...
As others have already noted, you could use a debugger for this. Most reasonably recent debuggers have some capability to break when a value is written to a particular variable (e.g., Visual Studio calls this a "watchpoint" or "data breakpoint" (depending on what age of IDE you're looking at), if memory serves. Dependi...
73,283,580
73,283,935
How can I decay const char that is passed as reference to a function with variadic parameters?
I have a function like this: void column(const std::string &value) { ... } void column(float value) { ... } template <class... TColumns> void row(const TColumns &...columns) { ImGui::TableNextRow(); (column(columns), ...); } I am using clang-tidy static analyzer to make sure that my code is always compliant with...
Since you anyways convert a c-string to a string each time you reach this line, it's suggested to have a static string. That is expected to solve the warning as well. #include <iostream> void column(const std::string &value) { } void column(float value) { } template <class... TColumns> void row(const TColumns &...col...
73,283,965
73,284,154
OOP Best Way To Call Similar Functions
Background: I have 2 similar blocks of code that I would like to merge together in a function. One block is for the x axis and the other is for the y axis. I have had this similar issue multiple times before and have shrugged it off since I assumed there was no better way of merging these in a clean fashion. Problem: H...
auto calcSpectrum = [&](int size, cv::Mat (cv::Mat::*memFn)(int) const) { vector<float> spectrum; for (int i = 0; i < size; i++) { auto tempVal = cv::mean((cleanImg.*memFn)(i)).val[0]; spectrum.push_back(tempVal); } return spectrum; } auto rowSpectrum = calcSpectrum(ROI.size().height, &...
73,284,075
73,284,891
Cap'n proto link error undefined symbol capnp::MessageBuilder::getRootInternal() arm
i am trying to build and link cap'n proto library using arm-linux-gnueabihf-ld and receive such link errors. also i am building it on docker and snapcraft. arm-linux-gnueabihf-ld: error: undefined symbol: capnp::MessageBuilder::getRootInternal() >>> referenced by main.cpp >>> CMakeFiles/feature-manager.di...
You need to link your binary against the libcapnp.so or libcapnp.a library. If you've installed the libraries to your system then the linker flag -lcapnp should accomplish this.
73,284,214
73,284,379
error: conversion from ‘unique_ptr<GreenStack,default_delete<GreenStack>>’ to non-scalar type ‘unique_ptr<Stack,default_delete<Stack>>’ requested
I am trying to assign a unique_ptr holding a derived class pointer to a unique_ptr holding a base class pointer. However, I am receiving the following error: error: conversion from ‘unique_ptr<GreenStack,default_delete<GreenStack>>’ to non-scalar type ‘unique_ptr<Stack,default_delete<Stack>>’ requested Code snippet i...
Define Stack::makeGreenStack(double) after defining GreenStack to be derived from Stack. The compiler will then know that a std::unique_ptr<Stack> can be initialized from a std::unique_ptr<GreenStack> class GreenStack; class Stack { public: explicit Stack(double initial_weight) : weight_(initial_weight) {} sta...
73,284,661
73,284,819
Pushing values in merge sort array
Im tring to learn basic data structures & algorithms. I have a problem with merging two sorted doubly linked lists.I have no idea why the last value doesnt push to merged list. As results for now for my code i get this. Left List: [(1)(3)(5)] Right List: [(-1)(2)(10)(20)] Merged: [(-1)(1)(2)(3)(5)(10)] Expected: [(-1)(...
For these lists Left List: [(1)(3)(5)] Right List: [(-1)(2)(10)(20)] when the left list achieves a null pointer the right list yet contains two nodes with values 10 and 20. However you are appending only one node if(lptr == NULL && rptr != NULL){ merged.pushBack(rptr->data); rptr = rptr->next; }else{ if(lptr ...
73,284,766
73,327,425
std::system::error exception during recursive_directory_iterator | Unicode Translation Exception 1113 in C++
I was working on a bigger project using the recursive_directory_iterator of std::filesystem, when I stumbled upon this seemingly unknown/unfixable error. I simplified the project to the bare minimum to recreate the error. Another questioner found a solution in providing the skip_permission_denied option, which does not...
SOOOOOOO I got the answer.. The problem originates from invisible (atleast for win10) unicode characters infront of a file ^^ How do you prevent that from crashing your programm? EZ, we first build our iterating for loop. EG like this: for (auto& dirEntry : fs::recursive_directory_iterator(pathToFolder)) // Iterates ov...
73,284,775
73,284,853
could not convert from ‘<brace-enclosed initializer list>’ to map
my code is as bellow: class A{ private: size_t linearProbing(T k, size_t i); size_t quadraticProbing(T k, size_t i); size_t doubleHashing(T k, size_t i); std::map<std::string, size_t (*)(T, size_t)> probeFunctionMap = { {"linearProbing", this->linearProbing}, {"quadraticPro...
A function pointer cannot store the state that you care about (aka this). You need to be able to store this state so that you can call using this later when you use this map. An example might be: std::map<std::string, std::function<size_t(T, size_t)>> The std::function will let you store the state. But you cannot crea...
73,284,968
73,285,022
const struct object access member functions (and an operator overloading question)
I tried to overload the << operator for my custom struct, but encountered error C2662, code as follows: struct HP{ int max_hp; int hp; HP(int max_hp){ this->max_hp=max_hp; this->hp=max_hp; } // this const declarative doesn't support const HP& obj argument const string repr(){ ...
const T func() {} means that the return type is const T and the function might mutate the object. Whereas, T func() const {} means that the return type is non-const but the object is unaltered (const). You can also have both or neither const. It doesn't have to be declared outside the class, it can be declared inside...
73,284,992
73,285,084
Cannot call DLL function
I have been trying to call a DLL that simply displays a MessageBox. I am running into issues where the loader will not locate the function. When the program is running, nothing happens. Tried using user32.dll which I know works for sure. Everything went fine with the SwapMouseButton function. I have defined my imports ...
Your DLL function does not have a calling convention specified, so it will use the compiler's default, which is most likely __cdecl NOT __stdcall. But your EXE is defining f_funci to use __stdcall. So, even if the function could be found, it likely won't be called correctly. Double-check the function's name mangling in...
73,285,120
73,285,597
C++ VS Code not recognizing syntax, unable to run code
I am using a specific syntax needed for a course, but when I use this C++ syntax in VS Code, it doesn't work and raises errors. Here is an example of the syntax that is not working: error: expected ';' at end of declaration int i {0}; ^ ; When I change it to int i = 0; the error disa...
Adding on to the comment above, this is what solved my issue: Go to this link: https://code.visualstudio.com/docs/cpp/config-clang-mac Go to the section Clang on macOS and scroll down to Troubleshooting. Follow the steps in this paragraph: "If you see build errors mentioning "C++11 extensions", you may not have update...
73,286,081
73,287,778
CMake command line define macro without value
I have the following line in my CMakeLists.txt add_compile_definitions(DEBUG=$(DEBUG)) so when I compile my code with Makefile, I can do this make DEBUG=1 But what I really want is to just define the DEBUG macro without setting any value to it. Is there a way I can do this on a command line with cmake?
With CMake you can, at configuration time, add some CMake variables. For example you can do this cmake -S <src_folder> -B <build_folder> -DDEBUG=ON. This way you will have access to the variable DEBUG in your CMake. In your CMake you will have this code if(DEBUG) add_compile_definition(DEBUG) endif() (Note that in...
73,286,101
73,289,770
pybind11 STL autoconverter breaks std::list pointers
I have a C++ library that manipulates (among other things) a list of wrappers that I have been working on converting to Python using pybind11. The rest of the library operates on a pointer to a list of pointers: std::list<Symbol*>*. The problem is that when attempting to autocast a Python list to this C++ list and then...
I don't know a lot about how pybind11 works its magic and therefore I can't help you understanding what is going on. However, I have the feeling that pybind attempts to build the list even though your code only uses a pointer to the list. If I were you I'd consider this a pybind bug and post it as an issue on their git...
73,286,188
73,286,474
Can a C++ function return without explicit giving type instantiation / with empty initializer list
Assuming a function with complicated return type, can we simplify the return statement?(no need to specify detailed return type) std::vector<std::map<int/*id*/, std::string/*data*/>> GetSomeData(int type) { if (type == DataType::Invalid) { return std::vector<std::map<int, std::string>>(); // this works return...
Yes, it can. {} can be used to initialize an empty std::vector<?>. This code can be compiled in gcc (Ubuntu 9.4.0-1ubuntu1~20.04.1) 9.4.0 with command g++ -o cpp-lab -std=c++11 main.cpp: #include <iostream> #include <vector> #include <map> #include <string> std::vector<std::map<int, std::string>> GetSomeData(int type)...
73,286,205
73,309,655
How to use Crow on Raspberry Pi
I'm trying to start a webserver using a Raspberry Pi for listening to POST requests from IFTTT. I'm programming in C++. I first tried Crow, which wouldn't work at all, giving the error "Handler function cannot have void return type...". I saw that others had also had issues with it, so I looked for a new solution. I fo...
Here's what I had to do (simple fix): In Geany: Go to Build > Set Build Commands Under both "compile" and "build", add the following text to the end of the string: -lboost_system Compilation is successful!
73,286,560
73,286,640
can anyone explain why my code gets runtime error in cpp?
Can anyone solve this runtime error? Status :Time limit exceeded Time: 5 secs Memory: 5.368 Mb Input 4 8 4 1 2 1 2 5 3 5 1 3 4 1 2 4 5 11 1 1 1 3 12 Runtime Error SIGTSTP #include <iostream> using namespace std; int main() { // your code goes here int n,m,k,cert=0; cin>>n>>m>>k; int a; for(int ...
It's because your code runs for a very long time. Look at this loop: for (int i = 0; i < k; k++) { k will increase, while i stays at 0 so i < k will always be true. When k at some point reaches its limit, INT_MAX, and you do k++, it'll will cause signed integer overflow and the program therefore has undefined behavior...
73,286,731
73,314,673
fgetc doesn't return to process
I'm trying to do something like echo {a:1} | prettier --stdin-filepath index.js and return the value returned in stdout. But I also want to make this program platform independant. Referencing this and this, I managed to write code like this: #include <Windows.h> #include <fcntl.h> #include <io.h> #include <iostream> #i...
The problem was I wasn't closing fd_IN before reading fd_OUT. This causes deadlock because prettier is awaiting input from program, and program is awaiting output from prettier. To fix this, fputs(source_code, fd_IN); fclose(fd_IN); std::string formatted_code; int c; while ((c = fgetc(fd_OUT)) != EOF) { ...
73,287,968
73,288,013
I don't understand why my sort on a string breaks everything
I have the following code: #include <algorithm> #include <iostream> #include <string> #include <vector> #include <unordered_map> using namespace std; vector<vector<string>> findAnagrams(vector<string> wordlist) { vector<vector<string>> result; unordered_map<string, vector<string>*> indexes; for (const string& ...
I'm guessing these lines are the main cause of your problem: { vector<string> vec = { word }; result.push_back(vec); indexes[wordSorted] = &vec; } Here you store a pointer to the local variable vec in the indexes map. When the block ends at } the life-time of vec also ends, and the pointer you just stored ...
73,288,009
73,289,096
How to feed multiple input into opencv dnn
I have a .pb model file. And I loaded the model using opencv's readnetfromtensorflow(). Now I want to use the model to generate predictions. There are 4 types of model input. Input data 256x256 image 64x64 image 64x64 image array (size is 4) output data array (size is 2) To generate the model's predictions, I first...
You can't set multiple inputs on a cv::dnn::Net.(It's not supported.) I suggest two alternatives. You do that DNN calculations with Tensorflow and other image/video tasks with OpenCV. You can wrap the data of a tensorflow::Tensor as a cv::Mat. (See Guillaume's answer in this question.) Redesign the functional model i...
73,288,015
73,288,059
What was the idiomatic way of reverse traversal of an iterable before C++11?
void rev(string& str) { for (auto i = str.end() -1; i != str.begin() -1; i--) cout << *i; cout << '\n'; } The code above works on my system however str.begin() -1 invokes undefined behaviour as per the standard. So what is the idiomatic way of reverse traversal using iterator's but not reverse_iterato...
This works for (auto i = str.end(); i != str.begin(); ) { --i; ... }
73,288,713
73,302,085
How to fetch RSA public key modulus and exponent in C/C++?
I'm using the BCrypt Windows library to handle the RSA algorithm in my application. Problem : I need to fetch the RSA public key modulus and exponent. In C# language, I was using the RSACryptoProvider class to fetch these informations (ExportParameters method). In my C/C++ application, BCrypt seems to be unable to fetc...
In fact, I did find a solution ! With the call of BCryptExportKey, the variable my_rsa_blob should have been a PUCHAR variable, which is a pointer to a string. With this, I found a link in Microsoft Docs while searching... The link is showing how the PUCHAR variable is designed : https://learn.microsoft.com/en-us/opens...
73,288,758
73,288,966
How can I create dynamic array without asking user to enter a size in C++?
I want to take 8 char password from user and then when she/he wanted to enter, I wanted it to be whatever size she/he enter. However, the code doesn't stop until it reaches 8 char, even I press 'enter', it takes it as a char and create '*'. I want its size to be whatever user write and then user press 'enter', it will ...
Your code is for (int i = 0; i < 8; i++) { inPass[i] = _getch(); _putch('*'); } Obviously that loops exactly eight times, doesn't matter what you type. If you want to stop the loop early then you must write the code to test for that possibility. Something like int inPassLength = 0; for (int i = 0; i < 8; i++) ...
73,289,715
73,291,534
Unpacking a tuple to call a function templated with variadic arguments in a subclass implementations (C++)
I am in the midst of implementing an Entity Component System. I am running into issues when attempting to call a function templated with variadic arguments: template <typename... Ts> struct engine_system : engine_system_base<Ts>... { using component_types = std::tuple<Ts...>; // subclass implements this vi...
Assuming component_view type is component_types, std::apply might help: void update(float delta_time) const { auto component_view = registry.get_view<Ts...>(); for (auto& c : component_view){ std::apply([&](auto&... args){ process_values(delta_time, args...); }, c); } }
73,290,108
73,290,317
C++ constructor call non-virtual function, let's say funcA, but funcA calls a virtual function, is it dangerous
I know we better don't call a virtual function in the constructor since the derived class construction not started yet based on https://isocpp.org/wiki/faq/strange-inheritance#calling-virtuals-from-ctors , but what's going on if we call a non-virtual function in constructor, but the non-virtual function call a virtual ...
if we call a non-virtual function in constructor, but the non-virtual function call a virtual one, is it dangerous as well? Yes. Take this example: struct foo { foo() { proxy(); } void proxy() { call(); } virtual void call() = 0; }; struct bar : foo { void call() override {} }; Instantiating bar wil...
73,290,146
73,290,463
Vector passed by reference inside lambda cannot be modified even if mutable keyword is used
I am trying to populate a vector with integer values which are coming in from standard input as follows: std::vector<int> v; for_each(v.begin(),v.end(),([&](auto &i) mutable {cin>>i; v.push_back(i);})); However, this statement is not working and the vector does not get filled with incoming values. Can you please sugg...
std::for_each applies the function object (the lambda) on each element in the passed container. Therefore to the parameter passed to the lambda is the current elements in the vector however, your vector is empty so there's nothing to iterate over so it never runs. You are also trying to assign the value from std::cin t...
73,290,446
73,290,551
read file in docker volume from docker container
I have a docker image of the osrm-backend on github. When I start the container a profile.lua script is run, which triggers a .cpp file to read the content of the file rastersource.asc. The path of that file gets defined in the lua script. The C++ file inside the image is located in scr/extractor/rastersource.cpp, the ...
If your file is at e:/docker/rastersource.asc on your host, it should be at /data/rastersource.asc inside your container. If your container has bash (for example) then it can be helpful to do something like docker run -it -v e:/docker:/data osrm/osrm-backend osrm-extract bash to run your container interactively, in or...
73,290,845
73,300,634
CLion doesn't sort include statements on commit
I'm using clang-format to define rules for sorting my include statements. This works perfectly when using the "Code > Reformat Code" button or pressing CTRL + ALT + L within a file. However, even when setting the "Reformat code" checkbox in the CLion commit dialog, the include statements don't get sorted when commiting...
JetBrains Support confirmed to be that this is a bug within CLion that they managed to reproduce on their system. Hoping for it to be fixed in a future version :)
73,291,186
73,291,445
How to define a unique object in a for loop in C++
I have java/python experience and recently started working on a C++ project. I ran into this very generic problem and wasn't able to find any clear answer/explanation in StackOverflow. The concepts behind is probably very basic, but still most of the things I tried seems to fail this far, so I thought it is worth to po...
std::unique_ptr<SomeObject> object = std::make_unique<SomeObject>(); objects.push_back(*object.get()); can be simplified to SomeObject object{}; objects.push_back(object); or even objects.emplace_back(); Your issue in 2nd/3rd snippet is that vector is resized, so inernal pointer and iterator are invalidated: test::S...
73,292,017
73,295,937
CMake FindFLEX produces NOTFOUND on windows
I installed flex and bison with chocolatey choco install winflexbison3 and created this CMakeLists.txt find_package(BISON) find_package(FLEX) message("FLEX_FOUND: ${FLEX_FOUND}") message("FLEX_EXECUTABLE: ${FLEX_EXECUTABLE}") message("FLEX_INCLUDE_DIRS: ${FLEX_INCLUDE_DIRS}") message("FLEX_LIBRARIES: ${FLEX_LIBRARIES}...
It's astounding how many irritating problems are caused by a trivial library file which probably shouldn't exist anyway, and which is hardly ever needed. The library in question was originally called libl (l for lex), and Posix requires that when you link executables which include a lex-generated scanner, you add -ll t...
73,292,407
73,292,900
How can I couple the lifetimes of two variables?
The following code compiles and runs fine, but does not work as intended (compare the comments in the code). I believe the reason is that the lifetime of is ends with getFileIter, so the stream buffer iterator has nothing left to iterate over. (By contrast, I think I remember that in C#, is would live as long as the st...
As one comment suggests, combine both things: stream and its iterator in a struct - to ensure the iterator will not outlive the stream: struct FileIter { FileIter(const std::string& p) : is(p), iter(is.rdbuf()) {} std::ifstream is; std::istreambuf_iterator<char> iter; }; std::cout << std::equa...
73,292,603
73,298,217
Printing a compile-time string_view
Say I have a metafunction that returns a std::string_view template<typename T> struct type_to_string; template <typename T> constexpr std::string_view type_to_string_v = type_to_string<T>::value; and a string_view resulting from this: constexpr auto sv = type_to_string_v<very_complex_expression>; Is there any way to...
Here's a modification of OP's solution that produces a somewhat more readable message with gcc. Unfortunately, with clang the message is rather less readable, and MSVC doesn't work at all (due to a compiler bug I suppose). #include <cstdlib> #include <algorithm> #include <string_view> #include <utility> template <size...
73,292,840
73,292,889
What is wrong in this program //trying to reverse an array?
I am trying to create a program to reverse an array by creating a temporary array defined within a fucntion and then copying the elements of the from the end of array to the start of the temporary array. #include<iostream> using namespace std; void reverse(int arr[]) { int revarray[10]; for(int i=0;i<10;i++) ...
In these nested for loops for(int i=0;i<10;i++) for(int j=9;j>=0;j--) { revarray[j]=arr[i]; } you are setting all elements of the array revarray with values of the array arr within the inner for loop in each iteration of the outer for loop. As a result after the loops all elements of the array revarray...
73,292,998
73,294,171
Destructor, when object's dynamic variable is locked by mutex will not free it?
I'm trying to solve some complicated (for me at least) asynchronous scenario at once, but I think it will be better to understand more simple case. Consider an object, that has allocated memory, carrying by variable: #include <thread> #include <mutex> using namespace std; mutex mu; class Object { public: char *var;...
Is is it possible that var will not be deleted in destructor? With ~Object() { mu.lock(); delete[]var; // destructor should free all dynamic memory on it's own, as I remember mu.unlock(); } You might have to wait that lock finish, but var would be deleted. Except that your program exhibits undefined be...
73,293,131
73,293,452
Start QProcess on button press
I'm building an application that launches an exe file on button press with QProcess. I have multiple buttons that are created in this way: Program reads from local database the information needed to create buttons (name, exe path) Then for each entry in the database it creates a button with the associated name in a pr...
I would use a lmbda like this: QSqlQueryModel query; query.setQuery("SELECT * FROM games"); if (!query.record(0).isEmpty()) { for (int i = 0; i < query.rowCount(); i++) { QPushButton* button = new QPushButton(query.record(i).value("name").toString(), ui->frame); button->setGeometry(120 * (ui->frame-...
73,293,281
73,293,332
Constructor of struct calling the member function of another class declared as a pointer
I have the following code: class Cohomology; struct EMField { std::unique_ptr<Cohomology> coh; std::array<DIM> data; EMField() {coh -> initializeField(*this);}; } class Cohomology { private: // private members public: Cohomology(PList params) { // Constru...
Just move the definition of EMField::EMField() until after both classes have been defined. class Cohomology; struct EMField { std::unique_ptr<Cohomology> coh; std::array<DIM> data; EMField(); }; class Cohomology { private: // private members public: Cohomology(PList params) ...
73,293,420
73,293,500
Const correctness in generic functions using iterators
I want to write a generic functions that takes in a sequence, while guaranteeing to not alter said sequence. template<typename ConstInputIter, typename OutputIter> OutputIter f(ConstInputIter begin, ConstInputIter end, OutputIter out) { InputIter iter = begin; do { *out++ = some_operation(*iter); }while(ite...
Even in C++20, there is no generic way to coerce an iterator over a non-const T into an iterator over a T const. Particular iterators may have a mechanism to do that, and you can use std::cbegin/cend for ranges to get const iterators. But given only an iterator, you are at the mercy of what the user provides. Applying ...
73,293,583
73,309,737
Using iterator to retrieve const values pointed to in containers
Const casting container value-types seems not possible. A comment in the other question suggests iterators as a solution, yet does not go into detail. Since I seemingly cannot simply convert a container from a non-const to a const version as a function parameter, I arrive at Iterators to maybe be able to do the job. I ...
Based on your situation, it sounds like defining a custom iterator with the semantics you want is the safe and simple way to go. It's technically correct, hard to accidentally misuse, and fairly fast, just requiring a shared_ptr copy on iterator dereference. I always recommend boost::iterator_facade or boost::iterator_...
73,293,661
73,304,759
What WinAPI feature could change the width of window border on Win7
I'm just noticed that a new version of my app has broader borders on Windows 7 (there is no difference in Win10): The background window is my new version and the foreground window is an older version. I'm trying to find difference in git, but with no luck yet. I have tried to set different border styles in resource ed...
It seems I've found the reason - I have switched Platform toolset from v120_xp to the latest v143. May be somebody knows how to retain thin borders with new toolset? UPDATE: Wow! Thanks to Hans Passant! When using newer version of toolset just set Minimum required version to 5.02. Now it works.
73,294,794
73,296,100
Replace text \n with actual new line. (C++)
I'm using C++ and I have a problem. Instead of creating a new line it prints \n. My Code: std::string text; std::cout << text; It prints:Hello\nWorld It was supposed to read \n as a new line and print something like this: "Hello World" So i've tried to use replace(text.begin(), text.end(), '\n', 'a') for testing purpo...
std::replace() won't work in this situation. When called on a std::string, it can replace only single characters, but in your case your string actually contains 2 distinct characters '\' and 'n'. So you need to use std::string::find() and std::string::replace() instead, eg: string::size_type index = 0; while ((index =...
73,294,887
73,296,263
Why does std::variant behave differently on GCC 8.5 and GCC 12.1 in respect to a `const char *` literal?
#include <iostream> #include <string> #include <variant> int main() { std::variant<std::string, bool> v{ "hasta la vista" }; std::cout << std::boolalpha << std::holds_alternative<std::string>(v) << ' ' << std::holds_alternative<bool>(v) << std::endl; } GCC 12.1.1 $ g++ std_alternative.cpp $ ./a.out true fal...
struct explicit_bool { bool b = false; template<class T, std::enable_if_t<std::is_same_v<T, bool>, bool> = true > explicit_bool( T v ):b(v){} explicit_bool(explicit_bool const&) noexcept=default; explicit_bool& operator=(explicit_bool const&)& noexcept=default; explicit_bool()noexcept=default; ~expli...
73,295,103
73,295,310
Passing variadic template parameter to another function with a variadic template parameter
I'm currently writing a logger for my engine and I've been stuck with a problem I could not solve. std::format takes in a constant string and a list of arguments after. My Log functions is as follows: template <typename... Args> void Log(const char* message, Args&&... args) Now in somewhere in the function scope, I tr...
This might get you started : #include <iostream> #include <format> template <typename... args_t> void Log(const std::string_view& fmt, args_t&&... args) { std::string formatted_message = std::vformat(fmt, std::make_format_args(std::forward<args_t>(args)...)); std::cout << formatted_message << "\n"; } int main...
73,296,287
73,304,211
Garbage value in rapid json AddMember
{ std::string result; RapidJSON::Value json; json.SetObject(); for(int i = 0; i < 5; ++i) { RapidJSON::Value data; data.SetObject(); for(auto it = HashMap.begin(); it != HashMap.end(); it++) { RapidJSON::Value arrObj; arrObj.SetObject(); ...
don't use stringRef, instead create a copy of the strings in both arrObj, data member Sample code RapidJSON::Value key(it2->first.c_str(), d.GetAllocator()); arrObj.AddMember(key, it2->second, d.GetAllocator());
73,296,745
73,296,855
C++ project crashes after glewinit()
(Im using Clion and Cmake on Macosx Intel chip) I wan't to make a Window Application with GLEW. But i get this error: Process finished with exit code 139 (interrupted by signal 11: SIGSEGV) I heard that you should define "GLEW_STATIC" in the preprocessing. But I have no idea how Clion works My main.cpp: #include "GL/g...
glewInit() requires a current OpenGL context to operate correctly. As written in your code glewInit() will fail and leave its glClear() function-pointer set to nullptr. Call glewInit() after glfwMakeContextCurrent() 'returns' GLFW_NO_ERROR and verify that it returns GLEW_OK.
73,297,830
73,297,875
Returning a reference to std::vector element results in a crash
The example below does not crash, but prints nothing with MSVC Compiler Version 19.32.31332 and prints "def" with GCC: #include <string> #include <vector> #include <set> #include <ranges> #include <iostream> template <class R, class Value> concept range_over = std::ranges::range<R> && std::same_as<std::ranges::range_v...
find2 takes the range by-value. So you are returning a reference into the function parameter object, which is a copy of the vector v in main, which in itself is very likely not the intention of the function. E.g. modifications through the returned reference would not be reflected in v. It is implementation-defined whe...
73,297,977
73,298,097
Why is VSCode using Cygwin to build and execute my CPP programs?
I downloaded and installed MinGW under C:\MinGw and installed g++ and gcc. If I run g++ --version I get: g++.exe (MinGW.org GCC-6.3.0-1) 6.3.0 Copyright (C) 2016 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS F...
VSCode uses a completely separate tool chain for compiling and for linting and syntax highlighting and similar. c_cpp_properties.json isn't for compiling. It gets the compiler typically from your PATH. See here. Your build task is probably set to the compiler g++, and the first one on the search path (the PATH environ...
73,298,338
73,298,496
what is the difference between "return num1<num2" and "return num2-num1" in comparator
I am learning how to write the comparator in C++. At first time, I return num1<num2, as a result I get a set in ascending order. Then I return num1>num2 and I get a set in descending order. Now I try to return num1-num2 which should equal to num1>num2 in my opinion, I get a set in descending order as predicted. But whe...
Now I try to return num1-num2 which should equal to num1>num2 in my opinion That is incorrect. Is there any difference between return num2-num1 and return num1<num2? Yes. num2-num1 returns an integer value that is the result of subtracting the value of num1 from the value of num2. Since your comparator returns a b...
73,298,399
73,298,639
C++ how can I simplify this if else statement?
I would like to know how I could simplify a statement like the one below. I have similar code everywhere, and would like to clear it up. if(isActive) { if(columnId == 4) g.drawText(active[row].value, 2, 0, width, height, Justification::centredLeft, true); } else { if(columnId == 4) g.drawText(in...
At first glance, it's most apparent that this code only does anything if columnId == 4. if(columnId == 4) { if(isActive) { g.drawText(active[row].value, 2, 0, width, height, Justification::centredLeft, true); } else { g.drawText(inactive[row].value, 2, 0, width, height, Justification...
73,298,741
73,298,986
SDL2 Transparency is super glitchy
(Source code and problem line at the bottom) I made a simple program to load a transparent PNG onto SDL2. However, it pops up as the image, with a very glitchy background that keeps flashing. I suspect this is a problem with my graphics card (M2 Macbook Air), but I do not know how to fix this. I think this because the...
Found a solution. Not sure why it solves the problem, but simply clearing the screen before drawing the texture fixes everything: while (is_running){ // Game loop stuff SDL_RenderClear(renderer); // Draw stuff... }
73,298,903
73,299,103
Default value for template parameter, followed by non-type parameter pack
I'm struggling to make this code work template <typename T, typename U = int, auto... Params> class Foo {}; int main() { auto foo1 = Foo<int, int, 1, 2, 3>{}; auto foo2 = Foo<int, 1, 2, 3>{}; // I want it to compile } It looks like I need some hack. I tried partial specialization, but it doesn't work either t...
Unfortunately due to the way that template deduction works, this is ...not going to work. Here's one alternative approach where the first template parameter is always a tuple, with one or two types, with the second type defaulting to an int: #include <tuple> template<typename T, auto ...Params> class Foo; template<ty...
73,299,054
73,299,146
GCC vs. Clang on the lifetime of temporary bound to an rvalue reference of another temporary
I want to figure out the lifetime of a temporary object S{} bound to an rvalue reference inside struct wrap<T>. wrap<T>::f() is a function that potentially interacts with the temporary; therefore, S{} must be alive when wrap<T>::f() is called. I consider two cases: (1) wrap{S{}}.f(); and (2) auto w = wrap{S{}}; w.f();....
clang is incorrect: both examples are valid and within lifetimes. The rule is that temporaries bound to references live as long as the reference (with some exceptions that don't apply here). Note that: auto w = wrap{S{}}; is exactly equivalent to: wrap<S> w{S{}}; And list-initialization directly binds (as opposed to ...
73,299,413
73,314,797
Change service systemd status from it's code
I have a C++ programm and it has two runtime states: active and waiting. I want to be able to change systemd status of the corresponding server (systemctl status) from the code. I have seen that there are "active (running)" and "active (waiting)" statuses in systemd. Is there any opportunity to do it? Or at least when ...
Those are systemd unit states and systemd manages them on its own, you can't directly set them. They are independent of the runtime states of your program. According to the systemctl manual, the state has three parts: load state (e.g. loaded, not-found) general unit state (e.g. acitve, inactive, failed) substate (e.g....
73,299,810
73,300,022
Is there a way to open a new terminal window with code in C++?
I have an application and I want it to somehow open a new command line window for input. Is there a way to do this with C++?
I'm not sure what is your "application" in this case. However, for applications to interact with each other, usually we would need some kind of APIs (Application Programming Interface), so that what you have on another application (a new terminal as you said) could be properly used in the "main" application. If your de...
73,300,085
73,300,126
i would like to know why my getName function isn't working
#include <iostream> #include <optional> using namespace std; void myFunction(optional<string> name = nullopt) { if (name == nullopt) { cout << "I wish I knew your name!" << endl; } else { cout << "Hello " << name.value() << "!" << endl; } } void getName(string Name){ cout << "input name: " << end...
You could just create a function with a return value instead.. #include <iostream> #include <optional> #include <string> using namespace std; void myFunction(optional<string> name = nullopt) { if (name == nullopt) { cout << "I wish I knew your name!" << endl; } else { cout << "Hello " << name.value() << ...
73,300,532
73,300,922
Linked List segmentation fault, class
Wrote this program in Cpp for Linked Lists. I am getting an error in insert when trying to insert at the front of the linked list as a segmentation fault. I couldn't print the list with list.printList(), but if I use push_back() and then printList(), it works fine. Spent a lot of time pondering but couldn't figure out?...
The root cause of the segmentation violation lies in the following lines: Node join = Head_node; (*a).setNextNode(&join); this->Head_node = (*a); You are storing the address of the function local variable join in the linked list. When the function returns, the pointer becomes a dangling pointer. Accessing that pointer...
73,300,768
73,301,125
Get number of tests ran by GoogleTest / fail on 0 tests run?
I'm using cmake's test runner to run several googletest test binaries. What I want to have happen is if a googletest test binary runs 0 tests via RUN_ALL_TESTS(), it fails. Currently, RUN_ALL_TESTS() returns success when it runs 0 tests. Alternatively, if I could somehow access the number of tests that RUN_ALL_TESTS() ...
To fail cmake test runner is easy. #include <gtest/gtest.h> int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); const int rv = RUN_ALL_TESTS(); if (rv != 0) return rv; #if 1 if (::testing::UnitTest::GetInstance()->test_to_run_count() == 0) return 1; #else if (::testing::UnitTest...
73,300,799
73,300,898
After about a minute, my openGL app freezes and "D3D12: Removing Device." is printed to the console
I am working on a simple openGL based (voxel) engine, and performing a lot of updates per frame to some vertex and buffer data. After about a minute or so of running, the screen freezes and D3D12: Removing Device. is printed to the console. The engine is pretty large, but i'll provide some of the important sudo code be...
I figured out the issue. I was calling buildBuffeer every tick, but never deleted previously created buffers. This caused my PC to run out of memory (at one point openGL was using 8GB of memory...). With a simple check, I was able to delete the buffer using the glDeleteVertexArrays function.
73,301,766
73,301,993
Can object’s property be used, if object used in another thread?
Can the example below make undefined behavior and crash when main thread try to call SetX, because, although x property is not being accessed in new thread, but object itself is? class Object{ public: int x; int y; Object(int x, int y) { this->x = x; this->y = y; } void SetX(int x) { this->x = x; } }*object = nullpt...
No there is no issue with accessing two different members of the same object. Note that both members are public and the setter doesn't do anything but set the member. Hence, you could rewrite ch to take a reference to obj->y as parameter and also in main, rather than calling SetX it could use int& x = obj->x;. Maybe th...
73,302,632
73,307,811
How to save high score in c++?
I create a small car game. But I can't save high score which is used next time when I play game again . So that I compare score. I using c++ language and #include<graphics.h> header file? Please help me? How to save score in graphics mode?
for me an easy solution is, as others users told to you, to store it using the file system, so the next time you need to get the highest score you can take it with ease, let me write you an example: #include<fstream> using namespace std; fstream fs; fs.open("score.txt",iOS::app);//ios::app is to append the text to the...
73,302,872
73,303,253
Cmake install nested static library target_link_library undefined reference
Install nested static library, and target_link_library not working File structure: HelloLib WorldLib CMakeLists.txt WorldLib.cpp WorldLib.h CMakeLists.txt HelloLib.cpp HelloLib.h CMakeLists.txt main.cpp main.cpp #include <iostream> #include "HelloLib/HelloLib.h" int main() { ...
The issue here is not the install process but the fact that you link only to libHelloLib.a. Your libHelloLib.a need the symbol in libWorldLib.a because libHelloLib.a is a static lib and so only contains its own symbol. It does not contains the symbol world that is defined in libWorldLib.a. To make your project works, y...
73,303,037
73,304,910
Why can mutex be used in different threads?
Using (writing) same variable in multiple threads simultaneously causes undefined behavior and crashes. Why using mutex, despite on fact that they are also variables, not causes undefined behavior? If mutex somehow can be used simultaneously, why not make all variables work simultaneously without locking? All my re...
As you have found, std::mutex is thread-safe because it uses atomic operations. It can be reproduced with std::atomic_bool. Using atomic variables from multiple thread is not undefined behavior, because that is the purpose of those variables. From C++ standard (emphasis mine): The execution of a program contains a dat...
73,303,179
73,322,124
C++ is quite slower than python in opencv
startTime = time.time() blob = cv2.dnn.blobFromImage(img, float(1.0/255.0), (frameWidth,frameHeight), (0,0,0), swapRB = True, crop = False) yolo.setInput(blob) layerOutput = yolo.forward(outputLayers) endTime = time.time() Python code that I am measuring the time auto start = chrono::steady_clock::now(); blob = blobFr...
I figured what the problem is, I have customized OpenCV for c++ to gain advantage of the CUDA cores in my Jetson Orin, yet the python uses general OpenCV stored in other directory, which doesn't have CUDA support. When I changed the OpenCV compilation for C++ to the general one, it worked fast as expected since in my c...
73,303,443
73,649,108
Need help in plotting coordinates from a nested vector using gnuplot. Also, plotting a Hough transformation with Gnuplot
Good day I have implemented Gnuplot 5.4 in my Visual Studio 2019 Community edition. Through a sample program, I can successfully print the content of an STL vector. Now the question arises whether it is possible to display a nested vector with X,Y value pairs? constexpr int WIDTH = 2; constexpr int LENGTH = 1280; vecto...
If anyone comes across this post I have the following solution. To visualise the Hough transform, I write every tenth theta and rho value of the Hough transform for a pair of X-Y values in a text document. This is done 18 times per X-Y value pair. fstream outputFile5; outputFile5.open("C:\\(...)", ios::...
73,303,581
73,303,923
Check if pubkey belongs to twisted Edwards25519
I want to check if some pubkey belongs to twisted edwards25519 (I guess this is used for ed25519 ?) The problem is that I have in theory some valid pubkeys like: hash_hex = "3afe3342f7192e52e25ebc07ec77c22a8f2d1ba4ead93be774f5e4db918d82a0" or hash_hex = "fd739be0e59c072096693b83f67fb2a7fd4e4b487e040c5b128ff602504e6c72...
You need to convert your hex string into binary format. Internally, the ed25519 functions work on a 256 (crypto_core_ed25519_BYTES (32) * 8) bit unsigned integer. You can compare it with an uint64_t, which consists of 8 octets. The only difference is that there is no standard uint256_t type, so a pointer to an array of...
73,303,801
73,312,352
Check if a different process is running with elevated privileges
I use 'elevated' here in the context of Windows UAC (i.e. Run as Administrator). Seemingly the standard way to check if a process is elevated is to use OpenProcess to get a handle to that process, then use OpenProcessToken to get an access token for that process, followed by GetTokenInformation() with the TokenElevatio...
Thanks to RbMm (and Hantalyte indirectly) I've been made aware that the Microsoft documentation for OpenProcessToken is incorrect in its assertion that the provided handle must have the PROCESS_QUERY_INFORMATION access permission, as it actually only requires that the handle have PROCESS_QUERY_LIMITED_INFORMATION (I ha...
73,303,868
73,304,226
static_assert not working inside class template definition
I'm trying to define a static member variable outside the class definition. It works as intended. But the static_assert that I placed inside the class definition does not compile for some reason. Why? The error message is: note: 'Foo<unsigned int>::var' was not initialized with a constant expression Commenting out the...
inline static const size_type var; That's all fine and dandy, but it does not mean that var is usable in a constant expression for every instantiation. There's the famous (infamous?) [temp.res.general]/8 The validity of a template may be checked prior to any instantiation. The program is ill-formed, no diagnostic req...
73,303,979
73,304,202
Code::Blocks returns -10737741819 (0xC0000005) when executing MySQL loop insert c++
I've been making program that need to continuously insert data to a database. I'm new to C++. I'm using xampp for my database. I want to make insert loop inside one of my function. my code looks like this #include "stdio.h" #include "fstream" #include "iostream" #include "mysql.h" #include "sstream" void loop(); void ...
Preferablly try this one. Your code is trying to connect database as many times as the loop proceeds. There is the description of that error from this link #include "stdio.h" #include "fstream" #include "iostream" #include "mysql.h" #include "sstream" void loop(); void print(); MYSQL* conn; const char* hostname =...
73,304,347
73,304,663
c++20: how to move capture a class instance
I want to construct a factory function for a class B, which needs a callback. The factory function gives a lambda to B, but this lambda needs an instance of another class A, which I want to create inside of my factory and move into the lambda. A is not copyable but moveable, so I would expect that this should be possib...
IMO, the reason is that the type lambda you passed to std::function ctor violate std::function type requirement, which needs the passed Callable must be CopyConstructible. Since the captured type A's copy constructor is deleted, it results that the lambda's copy constructor cannot be implicitly-declared. Here's some re...
73,304,543
73,305,787
I'm trying to write a char into a .txt file by using the ifstream getline function. But i get an Error Message
E0304 no instance of overloaded function "std::basic_ifstream<_Elem, _Traits>::getline [with _Elem=char, _Traits=std::char_traits]" matches the argument list Im using a struct for the Information: struct customer { int id; char name; char phone; char address; }; And im trying to write the Customers In...
There are big mistakes in your code that guys pointed out. You are not writing to the file, you are reading it. You cannot store a full name in a single character. Actually, if you want to store this data, you should use character array or std::string. So your struct will be like this : struct customer { int ID; ...