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,834,147
70,835,273
C++ overload assignment operator
I'm currently struggling with the assignment operator. I keep missing something. Could you help me out here? Check it out here https://godbolt.org/z/rfvTqcjoT class SpecialFloat { public: explicit SpecialFloat(const float f); SpecialFloat& operator=(const float f); private: float m_float; }; Spec...
The line SpecialFloat f = 1.0f; cannot perform assignment from 1.0f to f because f doesn't exist yet. We are just creating it. It would do if you had written SpecialFloat f{0.0f}; f = 1.0f [Demo]. The line SpecialFloat f = 1.0f; is doing copy initialization (1). Initializes an object from another object. Syntax T obje...
70,834,212
70,834,304
C++ const parameter directive blocks function use of class
I have a C++ class that is used as a function parameter which is causing me some grief. I can't seem to call function from the class parameter when it is designated as const. sample class: class FooBar { private: bool barFoo; // I want this modifiable only through functions public: const bool& getBarFoo() ...
const qualifier of a member function is not necessarily the same as the const qualifier of its return type. Actually they are unrelated in general (only when you return a reference to a member, from a const method one can only get a const reference). Your method: const bool& getBarFoo() // this function needs to be use...
70,834,499
70,835,752
Runtime error: signed integer overflow: 3 * 965628297 cannot be represented in type 'int'
I am solving a problem of code forces. Here is the problem link -> Problem Link My code passes 9 test cases out of 10 and the 10th case is this 100 ??b?a?a???aca?c?a?ca??????ac?b???aabb?c?ac??cbca???a?b????baa?ca??b???cbc??c??ab?ac???c?bcbb?c??abac and the error I got is this wrong answer expected '331264319', fou...
Since you need the result "modulo 10^9+7", you can reduce the result of all additions and multiplications "modulo 10^9+7" (i.e. find the remainder after division by 10^9+7 - this is what the % operator does). In the code, you can either do this in each calculation or at the end of the loop. Applying the first option (a...
70,834,618
70,836,001
Z3 and let statement in C/C++
SMT-LIB support a let statement: (let ((x1 t1) · · · (xn tn)) t) Which statements must be used if the C/C++ library of Z3 is being used?
There's no corresponding statement in C/C++, because it is not needed. Note that SMTLib's let statement allows you to give a name to a subexpression so you can use it multiple times. If you want to do the same thing in C/C++, you'd simply use a C/C++ variable (of the right type) that contains that expression, and use i...
70,834,849
70,835,915
QT C++ to QML can not be connected
I have the following code: class Boundaries: public QObject{ Q_OBJECT enum Type{ in, out }; QDateTime m_startTimeBoundary{}; QDateTime m_endTimeBoundary{}; QDateTime m_from{}; QDateTime m_to{}; Q_PROPERTY(QDateTime fromDate READ...
To my understanding with myCustomModel.myClass.myClassIn(_org, diff) you are trying to invoke a function of an object from your C++ environment but you are actually creating a new instance of type MyCustomModel which requires QML to know of the class Boundaries Instead of registering the type (qmlRegisterType) to make ...
70,835,208
71,268,759
Need some assistance in understanding FBX SDK data structures
I am attempting to convert the animation of some older files over to the FBX file format in order to import them into the Unreal engine. I am currently going through the data structures and see how what I have can relate to the FBX data structures. I have a few questions that I am asking the community to help me in my ...
Do I have to attach a skeleton within the FBX file format? FBX uses FbxAnimCurveNodes to link FbxAnimCurves to animatable FbxObject properties (such as translation and rotation). Therefore, if you omit the skeleton from the file, then FbxAnimCurveNodes theoretically become useless, and all you're left with are generi...
70,835,747
70,837,216
Access a struct variable when struct is passed as a double pointer
I have a function as follows int check_inband_status(Port **ePort, Port **wPort, InbandPort *inbandPort) { std::ifstream ring_config_file(RING_CONFIG_FILE); Json::Value ring_config; ring_config_file >> ring_config; (*ePort)->port_id = ring_config["east_p...
You're passing the addresses of null pointers, so both *ePort and *wPort are null. And then you dereference them, and it goes boom. The function is probably supposed to (dynamically) create new objects and assign their addresses to *ePort and *wPort. It's not obvious what type of objects to create, but I would expect i...
70,836,002
70,836,248
Constructors for different ways of initialisation
I was writing code on class Matrix. So I have a small difficulty in understanding how constructor is used. Actually I have particular doubt on default constructor and parameterized constructor. Default constructor of class : Matrix() Initialise rows and columns and matrix elements zero. Parameterized constructor: Matri...
There is much wrong in your code. You cannot use rows and columns as array size when they are only known at runtime. Even if you could use row and columns as array size, you are using them as size of the array before you assign any value to them. Moreover this->mat[rows][columns]={0}; tries to access one element that i...
70,836,396
70,836,756
Use child variable without to rewrite function Class
I have a question is possible to use children variable for display something. For example: // Entity.hpp class Entity { public: Entity(); ~Entity(); // For this function virtual void attack(); virtual int getNbAttack(); protected: private: int _nbAttack = 0;...
You can absolutely do that. But you need to make a few changes to the code you posted: add Entity as base class to the class definition of Player (it is missing after public) make the data members of Entity protected or add protected setters for them if you want to use the base class' constructors in your derived clas...
70,836,505
70,836,853
C++20: Implement std::is_constructible using concepts
Is there a portable way to implement std::is_constructible using concepts without STL using requires expression or template metaprogramming only? Consider this code: template <class T, class... Args> struct is_constructible : std::bool_constant<requires { new T(std::declval<Args>()...); }> { }; It works ...
No. Certainly not "cleanly and nicely". In fact, early proposals during the standardization process attempted to implement constructible_from using requires expressions, but there were so many corner cases that we gave up and specified it in terms of the type trait instead.
70,836,549
70,894,727
Old xlib programs hang the Linux GUI on window resize. Why?
I have noticed, that with the older X programs, when the user start to resize window by dragging its edges, the whole GUI of the OS freezes. I am testing with glxgears - the gears stop rotating. The same happens with the content update of all other programs - such as the task manager, terminal windows and so on. After ...
Well, after some research I have found the answer. The problem is that the old programs does not use the _NEW_WM_SYNC_REQUEST protocol in order to synchronize their ability to redraw the window content with the rate of the resize events from the window manager. Because of this the window manager resizes the window in t...
70,836,591
70,960,003
Low quality QPixmap in Windows
I am uploading QPixmap to QTableView via QSqlTableModel. On Linux, images are displayed in normal quality, but on Windows, the image quality is very low. Is it possible to fix it somehow? Qt 6 fragment of my code: SqlTableModel::SqlTableModel(QObject *parent, QSqlDatabase db) : QSqlTableModel(parent, db) { int ...
Yes, I fixed it. The problem is detected if the interface scaling is enabled in the Windows 10 OS settings (in my case it is 125%). It wasn't immediately clear. The problem is fixed as follows: SqlTableModel::SqlTableModel(QObject *parent, QSqlDatabase db) : QSqlTableModel(parent, db) { auto pixelratio = qApp->pr...
70,836,668
70,836,669
Allocating structs of arbitrary constant size on the stack
I've written a small working plugin server. The plugins are implemented using .so shared objects, which are manually loaded during runtime in the "server" by calls to dlopen (header <dlfcn.h>). All of the shared object plugins have the same interface: extern "C" void* do_something() { return SharedAllocator<T>{}.al...
Actually, I just found a solution. It boils down to inverting the direction in which the memory location for the allocation of T is passed around. Is there any way for do_soemthing_proxy to allocate the effective size of T on its stack? Maybe. But what the code actually needs is an allocation of the effective size of...
70,837,571
70,837,748
How to initialize a shared_ptr to a QTextCodec in my constructor?
I am trying to initialize a shared_ptr to a QTextCodec (Qt class for charset conversion) in my class constructor. This is the code I have where I get a ‘virtual QTextCodec::~QTextCodec()’ is protected within this context error: myencoder.h #ifndef MYENCODER_H #define MYENCODER_H #include <memory> #include <QTextCodec>...
From docs: QTextCodec::~QTextCodec ( ) protected virtual Destroys the QTextCodec. You should not delete codecs. Once created their lifetime becomes the responsibility of CopperSpice. Same with the incorporated version: QTextCodec::~QTextCodec() ...
70,839,287
70,839,339
candidate template ignored: could not match 'function<type-parameter-0-0 ()>' against 'double (*)()'
I am trying to use a template that takes in an std::function, but the template argument deduction is failing. double foo(){ return 2.3; } template <typename V> void funcC (V (*fptr)()){ std::cout << "C function's value is\"" << fptr() << '\"' << std::endl; } template <typename V> void funcCxx (std::function<V()> ...
It cannot be deduced because you are not passing a std::function to funcCxx. Function argument and parameter type must match in template argument deduction. Otherwise deduction fails. You could let the function take any type instead of constraining it to function pointers or std::function and then you can construct the...
70,839,540
70,839,674
deduced return type depedent on member function template argument
I am trying to figure out what's wrong with this code: #include <string> struct Bar { using Deduced = typename std::string; }; class Test { template<typename Foo> auto Func() -> decltype(Foo::Deduced) { return Foo::Deduced(); } }; int main() { Test t; std::string ret = t.template...
Remove the decltype. decltype gives the type of an expression. But Foo::Deduced is already a type, so you can't apply decltype to it. You simply want to refer to that type itself. So all you have to do is write Foo::Deduced. However, in some contexts, you need to prefix it with typename to tell the compiler that it's r...
70,839,660
70,839,688
std::max with overloaded less operator doesn't compile
Here's the code: #include <iostream> #include <fstream> #include <string> #include <algorithm> #include <utility> struct student { std::string full_name; int group; int number; friend std::istream& operator>>(std::istream& in, student& obj) { in >> obj.full_name >> obj.group >> obj.number;...
You are missing a const qualifier on comparison function: #include <algorithm> #include <fstream> #include <iostream> #include <string> #include <utility> struct student { std::string full_name; int group; int number; friend std::istream& operator>>(std::istream& in, student& obj) { in >>...
70,839,790
70,882,789
How reliable is the format of demangled names?
I am working on a pretty dynamic C++ program which allows the user to define their own data structures which are then serialized in an output HDF5 data file. Instead of requiring the user to define a new HDF5 data type, I am "splitting" their data structures into HDF5 subgroups in which I store the different member var...
Unreliable. If you compile with the same compiler on the same OS then you should have some stability — but that is absolutely not guaranteed. ABI changes in name mangling can happen at any time in a compiler’s release cycle. Individual compiler teams may have some information about this in their documentation. I am not...
70,840,151
70,840,227
Operator new behaves differently in Debug mode than in Release mode in MSVC
While testing some things regarding page faults I discovered a curious difference between how new operates in Debug mode and Release mode in MSVC. Consider the following code1: #include <array> constexpr size_t PAGE_SIZE = 4096; int main() { const size_t count = 1000000; char* const mem = new char[PAGE_SIZE *...
To understand what happened you need to know two things: The debug builds do a lot of cool stuff for you to help you find bugs. One is writing a known value into the program's memory so you'll more easily recognize that you've messed around with uninitialized storage. Modern memory management systems in CPUs are com...
70,840,406
70,845,460
Why is member function return type instantiated much later than the expression types it depends on?
Pardon the confusing title. I have this code, which is accepted by GCC, Clang, and MSVC: #include <type_traits> template <typename T> struct Reader { friend auto adl(Reader<T>); }; template <typename T, typename U> struct Writer { friend auto adl(Reader<T>) {return U{};} }; struct A { struct Tag {}; ...
The declaration auto helper() -> Writer<Tag,decltype(this)>; doesn't cause instantiation of Writer<Tag,decltype(this)> because the return type is not required to be complete. The definition of helper() and with it the implicit instantiation of Writer<Tag,decltype(this)> are then in a complete-class context, which it se...
70,840,420
70,840,529
For some reason, when i use getch() my program crash, but if i use cin, then it works
I would like to know what knowledge I lack about inputs of arrays. I want to input one character and then automatically go to the next line of the code. Here is the code: char word[21]; for(int i = 0;i < 21; i++) { word[i] = getch(); //cin>>word[i]; if(word[i] == '/')break; } for(int j = 0;j < strlen(word);...
Here's how I would do this: char c; std::cin >> c; // Input the character. std::cin.ignore(10000, '\n'); // Ignore remaining characters on the line. You could replace 10000 with the maximum value for unsigned integers, but I just use an improbable large number (to fuel the improbability drive).
70,840,467
70,840,496
Difference between foo = bar and foo{ bar }
I was under the impression that foo = bar and foo{ bar } both did the same thing and it was just a matter of preference, but in my code foo = bar gives an error but foo{ bar } does not: std::vector<std::unique_ptr<bar>> bars; bar& myFunction() { bar* b = new bar(); std::unique_ptr<bar> foo{ b }; //works fine ...
The second one does not work because unique_ptr has an explicit constructor: explicit unique_ptr( pointer p ) noexcept; The below line: std::unique_ptr<bar> foo = b; tries to call the above-mentioned constructor of std::unique_ptr. And because of the explicit keyword, that call to the constructor is invalid. So only ...
70,840,683
71,201,077
Installed Visual Studio 2022 but 'cl' is not recognized as an internal or external command
None of my terminals on Windows 10 recognize cl 'as an internal or external command'. I have Visual Studio 2022 installed and I've tried it on every terminal, including terminals in the Visual Studio 2022 under the Start menu. I've tried the other solutions to Stack Overflow. I tried setting an environment variable of ...
Please find in your system this path: C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.31.31103\bin\Hostx64\x64 and add this path in the user variable path for your user name in the edit system environment variables. this will work.
70,840,857
70,939,098
push-buffer is invalid for instance of type GstWebRTCBin
Hi i am trying to push data into a webrtcbin of Gstreamer. this is my pipeline which works fine with testdata pipeline = gst_parse_launch("webrtcbin " "name=webrtcbin stun-server=stun://stun.l.google.com:19302 " "appsrc ! videorate ! " "video/x-raw," "width=1280," "h...
So i found my problem, and as alyways it was very simple but for me hard due to the lack of knowledge in gstreamer i tried to push the signal against the webrtcbin wbile i should have been pushing against the appsrc. these are different units. so i gave the appsrc a name: "webrtcbin name=webrtcbin stun-server=stun://st...
70,841,664
70,842,719
Best way to group string members of object in a vector
I am trying to store a vector of objects and sort them by a string member possessed by each object. It doesn't need to be sorted alphabetically, it only needs to group every object with an identical string together in the vector. IE reading through the vector and outputting the strings from beginning to end should retu...
Seems like Functor or Lambda is the way to go for this particular program, but I realized some time after posting that I could just create an ID for the images and sort those instead of strings. Thanks for the help though, everyone!
70,841,798
70,842,170
What is the best way to implement mehtods of generic class (c++)
I want to implement a class of dynamic array in c++, and I want this implementation to be generic. Consider the following definition: ef DYNAMICARRAY_H #define DYNAMICARRAY_H template<class T> class DynamicArray { public: DynamicArray(); virtual ~DynamicArray(); protected: private: }; #...
On the other hand, as I understand, implementing such a function in the header file might cause the compiler to make the function an inline function. Note 1: All functions defined in the class are "inline". Note 2: All functions in the header files (not in the class) should have the inline keyword added by the engine...
70,841,978
70,842,114
Retrieving the file path of a dynamic library loaded by a process on MacOS
Goal: I want to retrieve the file paths of dynamic libraries loaded by a process. My code: struct task_dyld_info dyld_info; mach_msg_type_number_t count = TASK_DYLD_INFO_COUNT; struct dyld_image_info dyld_image_info; char path[PATH_MAX]; if (task_info(task, TASK_DYLD_INFO, (task_info_t) & dyld_info, & count) == KERN_S...
According to https://gist.github.com/xcxcxc/989018646b1f0f2f31f0873a32c4a658, you need to use vm_read to get that data.
70,842,288
70,842,660
OpenGL: Segmentation Fault (Core Dumped) when running
I am writing a game engine in C++ and OpenGL and when I open my first test window i receive this issue: Segmentation fault (core dumped) There is no error when compiling, and it compiles just fine. The problem lies when I go to open the window. HOW TO REPRODUCE: #include <glad/glad.h> #include <GLFW/glfw3.h> #include ...
glfwGetProcAddress() will only (potentially, depending on the name requested and the GL version of the current context) return usable, non-NULL function-pointers if a GL context is current. With GLFW you make a window's context current via glfwMakeContextCurrent() so if you truly want to grab your own pointer to glGenB...
70,842,697
70,848,219
Problem with inheritance from abstract class which is also template (c++)
I defined the following abstract List class: #ifndef LIST_H #define LIST_H template <class T> class List { public: List(); virtual bool isEmpty() const=0; virtual void Set(int index, T value)=0; virtual int getSize() const=0; virtual void add(T value)=0; virtual T R...
Add a constructor List(int) to the base class which initializes the m_size field. template <class T> class List { public: List(); List(int _size): m_size(_size) {}; // .... protected: int m_size; }; Add this constructor to the initializers of DynamicArray: template<class T> class D...
70,843,269
70,844,276
In C + + singleton mode, if I modify a member variable in two member functions, will it conflict?
In C + + singleton mode, if I modify a member variable in two member functions, will it conflict?Do I need a mutex? for example: class Teacher { int var; int func1(int a) { var = a; } int func2(int b) { var = b; } ... } what is "singleton mode" in c++? I defin...
First off: 'Singleton' is a design pattern, not a 'mode'. (Personally I prefer using a namespace and static variables in the compile unit to represent 'only one instance', but that's a matter of taste). Regarding your actual questions, unless threads (or interrupts) are involved, all accesses are sequential, which mean...
70,843,689
70,854,890
How to refresh a Groupbox control in MFC (C++)
I created a Groupbox in my MFC view class. But failed in refresh it while Restore Down from Maxmize as well as Maxmize from Restore Down. I create the Groupbox in View::OnCreate: int Cmfc_gui_test3View::OnCreate(LPCREATESTRUCT lpCreateStruct) { ... CRect mybox( 0, 0,350, 1000); pmyGroupBox->Create(_T("Test GroupBox")...
This question (Can a MFC dialog resource be attached to a CChildView?) should provide useful information. You need to use the CFormView class if you want to create a form that has controls on it, like combo boxes. There are some other useful articles on this subject: Q98598: HOWTO: Use CFormView in SDI and MDI Applicat...
70,843,952
70,848,455
Do modern c++ compilers optimize assignments after type casting?
Take the following code: char chars[4] = {0x5B, 0x5B, 0x5B, 0x5B}; int* b = (int*) &chars[0]; The (int*) &chars[0] value is going to be used in a loop (a long loop). Is there any advantage in using (int*) &chars[0] over b in my code? Is there any overhead in creating b? Since I only want to use it as an alias and impr...
is it OK to do this kind of type casting as long as I know what I'm doing? No, this is not OK. This is not safe. The C++ standard does not allow that. You can access to an object representation (ie. casting an object pointer to char*) although the result is dependent of the target platform (due to the endianess and p...
70,844,568
70,886,709
free'ing pointers inside a container before clear()
I have a container such as this: std::unordered_set<char*, Hash, Equal> my_set; I want to free the char*'s inside this container before I .clear() it, so I do, for(auto i : my_set){ free(i); } my_set.clear(); But this means, before the .clear(), the container is corrupted. I am inclined to think that this is norm...
But this means, before the .clear(), the container is corrupted. The container is not corrupted. It stores char*s, which can be thought of as numerical addresses at which text might be stored. If valid text is no longer stored at those addresses, that's perfectly fine as long as no attempt is made to follow/derefer...
70,844,884
70,845,237
Why most of C++ STL library functions use iterator as parameter?
I not getting a clear difference between pointers and iterators. Can anyone help? Thank you in advance.
I not getting a clear difference between pointers and iterators. Iterator is a concept of a type whose instance that can point to an object, and that can be incremented to point to the next sibling element. A pair of iterators pointing to the same container represent a range of objects within the container. Pointers ...
70,844,982
70,845,022
C++ class does not output correct data?
No compilation error but the output is this: g++ class.cpp && ./a.out is -1003073000 years old. It does not output the string and int as it supposed to be. I don't know what is wrong, I would really appreciate if someone point out my mistake, thanks!. Here is the code: #include<iostream> class Student{ private: ...
In the constructor Student(std::string name, int age){ name = name; age = age; } The names name and age are the argument variables of those names. Which means you assign the variables to themselves. That will leave the Student::name member default constructed and empty, but the Student::age variable wi...
70,845,208
70,854,660
Im trying to convert a hexadecimal number to decimal number in C++
This is what I have so far: #include <iostream> #include <cmath> #include <string.h> using namespace std; int main() { string hexa = "1A"; // cout<<"HEXADECIMAL TO DECIMAL\n"; // cout<<"ENTER HEXADECIMAL: "; // cin>>hexa; // int inc1 = 0, hex1, ans, total = 0; int ...
#include <iostream> #include <string> using namespace std; int main(){ string s; cin>>s;//input string int ans=0;//for storing ans int p=1; int n=s.size();//length of the string //travarsing from right to left for(int i=n-1;i>=0;i--){ //if the character is between 0 to 9 if(s[i]>='0'&&s[i]<='9'){...
70,845,475
70,845,528
How long does a non capturing lambda live?
If I have some c++ code that looks roughly like this: void (*fun_ptr)(int); void Test() { fun_ptr = [](int i) { /* do stuff */ }; } int main() { Test(); /* do stuff */ fun_ptr(0); return 0; } Can I expect that function pointer to live forever? Or is it like structs and it's only valid for as long as...
fun_ptr doesn't point to a lambda. It effectively points to a static function (defined in the lambda class), and this function doesn't need a living lambda to work.
70,846,124
70,846,185
How to deduce order of two variables store/load with acq/rel order?
I am trying to learn about execution order involving atomic variables in C++, and I have the following code. According to cppreference, I have the following reasoning: C++ enforce 1->2 order when executing Because no load/store can be moved before an acquire-load within the same thread. C++ enforce 3->4 order when ex...
1 will "happen before" 2, and 3 will "happen before" 4. This part is correct. However, for 3 to "synchronize with" (and "happen after") 2, it must successfully read the value written by 2. If it doesn't read that value (because it ended up running before 2), then no synchronization happens, and no ordering is imposed o...
70,846,440
70,869,591
How to call a python function from C++ with pybind11?
Please consider the following C++ pybind11 program: #include <pybind11/embed.h> namespace py = pybind11; int main() { py::scoped_interpreter guard{}; py::dict locals; py::exec(R"( import sys def f(): print(sys.version) )", py::globals(), locals); locals["f"](); /...
So the initial problem (solved in the comments) was that having different globals and locals causes it to be evaluated as if it were in a class (see the Python documentation for exec - the PyBind11 function behaves basically the same): Remember that at the module level, globals and locals are the same dictionary. If e...
70,846,881
70,846,986
Why c++ .find() method is not working properly?
I am writing a code to determine how many characters in string s are also in j Here is my code: string j,s; cin >> j >>s; int count=0; for(int i=0;i<j.size();++i){ if(s.find(j[i])){ ++count; } } cout << count+1 << endl; The problem is that s.find is not work for j[0] and When a user enters none as str...
string::find does not return a boolean, but the position of the matching character (from 0 to size()-1) or string::npos if it doesn't find anything. https://en.cppreference.com/w/cpp/string/basic_string/find Use if(s.find(j[i]) != std::string::npos) instead.
70,846,942
70,847,902
Creating a filesystem file in C++
Is there a way to create a filesystem file that can be mounted in C++? I want to make a file containing a NTFS filesystem and mount it to a new partition. I want this done in C++ in Windows. Is there a library and perhaps some code examples that does this? I know windows has the diskpart tool which does exactly that bu...
To really "mount" the filesystem (ie. to be able to just "fopen" something inside that filesystem) you need support from the kernel. Either you let your operating system take care of it completely (e.g the VHD commands on windows; example use on stackoverflow). Alternatively can use libfuse/winfsp to interact with the ...
70,847,346
70,848,255
Difference between returning and not returning in recursion
I have written a program to print the Kth node from root of a binary tree. // PRINT KTH NODE FROM ROOT (FUNCTION 1) void printKth(node *root, int k){ if (root == NULL){ return; } if (k == 0){ cout<<root -> data<<" "; return; } printKth(root -> left, k-1); printKth(root -...
There is nothing special about recursive functions. The second you return you are no longer evaluating the rest. You see that in your base cases since they don't evaluate the rest. When you add return the result of the call is returned and the last statement is never reached. You function doesn't print the kth node but...
70,847,581
70,847,656
Error while using a static data member template
I am trying understand the concept of static data member templates. And i came across the following example in a book: class Collection { public: template<typename T> static T zero = 0; }; When i try to execute the program it gives the error that: undefined reference to `Collection::zero<int>' To s...
Yes this is a typo in the book. The problem is that you've specified an initializer for the static data member template even though it is not inline. Solution There are 2 ways to solve this problem both of which are given below. Method 1: C++17 In C++17, you can make use of the keyword inline. class Collection { pu...
70,848,303
70,848,588
Why is the boost server class throwing runtime error
I am getting a runtime error in the following code: boost::asio::io_context io_context; server server1(io_context, 1980); boost::thread t(boost::bind(&boost::asio::io_context::run, &io_context)); Where the definition of the server class is: using boost::asio::ip::tcp; class server { public: server(boost::asio::...
It seems your code is missing a listen. On my Linux box this simply doesn't do anything, but perhaps on Win32 it throws an error due to invalid state of the acceptor when doing async_accept? Here's a simple tester that does what is expected on linux: #include <boost/asio.hpp> #include <iostream> using boost::asio::ip::...
70,848,803
70,848,849
explicit template instantiation of explicit operator bool
I'm trying to understand why I get a linker error ( error LNK2001: unresolved external symbol "public: __cdecl Foo<int>::operator bool(void)const_ ) With the following code. If I move the definition of Foo::operator bool() to the header, it builds fine. Apparently there is a problem with the explicit template instan...
An explicit template instantiation must have the template definition visible. So you have to put template Foo<int>::operator bool() const; in Foo.cpp, not main.cpp. Demo
70,848,994
70,850,762
Weird C2143 error with two consecutive if constexpr in the same function
I am compiling the following code with c++17: #include <iostream> struct A { void barA() const {std::cout << "barA\n";} }; struct B { void barB() const {std::cout << "barB\n";} }; template<typename T> constexpr bool isBaseA() { return std::is_base_of<A, T>::value; } template<typename T> constexpr bool i...
Looks like a parser bug, as adding parentheses avoids the error. Adding parentheses should have no effect at all in this context: template<typename... Args> class K : public Args... { public: void foo() { using MyK = K<Args...>; // extra parentheses to overcome MSVC error if constexpr((isBaseA<MyK>()))...
70,849,136
70,849,299
how to pass an array through to another function? c++
so i am making a program that takes student data as objects and prints it, i am trying to store the data as an array so each student is a element in the array, i am having issues with printing the data though as i cannot pass the array into the print function, can anyone help? when i try and compile i get "studentarray...
You wrote student printstudent(student & studentarray); which looks more like a deceleration than a function call. I'm guessing you wanted to write printstudent(studentarray)? Your error is caused by declaring printstudent(student& studentarray[10]) , which declares the function argument to be an array of 10 student& i...
70,849,604
70,850,122
How to efficiently handle incoming delayed events on a single timeline?
I want to implement the algorithm that awaits for some events and handles them after some delay. Each event has it's own predefined delay. The handler may be executed in a separate thread. The issues with the CPU throttling, the host overload, etc. may be ignored - it's not intended to be a precise real-time system. Ex...
Another approach is to have a single thread that sleeps between events. But I can't figure out how to forcefully "wake" it when there is a new event that should be handled between now and the next scheduled wake up. I suppose solution to these problems are, at least on *nix systems, poll or epoll with some help of ti...
70,849,892
70,851,101
Why does std::basic_string_view have two equality comparison operators?
A quote from the standard regarding std::basic_string_view equality comparison operators (see http://eel.is/c++draft/string.view#comparison): [Example 1: A sample conforming implementation for operator== would be: template<class charT, class traits> constexpr bool operator==(basic_string_view<charT, traits> lhs, ...
I think this is insufficient reduction as a result of the adoption of <=> in P1614. Before that paper, there were three ==s in the example: template<class charT, class traits> constexpr bool operator==(basic_string_view<charT, traits> lhs, basic_string_view<charT, traits> rhs) noexcept...
70,850,115
70,854,390
What is a pre-allocated buffer, and how should you use one?
I am studying FreeRTOS, and in their tutorial book they talk about using "a pool of pre-allocated buffers" for holding pointers to char[] arrays (to pass between tasks via a queue). In the example found in Chapter 4.5 Working with Large or Variable Sized Data, they reference this sudo function called prvGetBuffer() and...
A pool is a collection of shared items such as a secretarial pool or motorpool. A pool of pre-allocated buffers is a pool of chunks of memory. Typically all the chunks in the pool are the same size. The application can allocate a chunk from the pool, use the memory as needed, and then return the chunk to the pool whe...
70,850,583
70,853,606
Program to evaluate postfix expressions but there is a wierd problem with this program-it does not gives output and instead gives a long error
I was writing a code for postfix expression evaluation and encountered a weird error. it shows a big error which is really difficult for me to understand what is wrong in the code. it would be really helpful if you please have a look and tell me what's wrong with it or what mistake I have made. I have listed the code b...
Your problem is that you're trying to compare a std::string with a char: if (expression == ' ' || expression == ',') Change it to: if (expression == " " || expression == ",") The string class doesn't support comparisons with single characters, hence the error. Also, this is wrong: int a = stoi(expression[i]); stoi n...
70,850,760
70,888,236
parallel programming multiplying two arrays of numbers
I have the following C++ code that multiply two array elements of a large size count double* pA1 = { large array }; double* pA2 = { large array }; for(register int r = mm; r <= count; ++r) { lg += *pA1-- * *pA2--; } Is there a way that I can implement parallelism for the code?
Here is an alternative OpenMP implementation that is simpler (and a bit faster on many-core platforms): double dot_prod_parallel(double* v1, double* v2, int dim) { TimeMeasureHelper helper; double sum = 0.; #pragma omp parallel for reduction(+:sum) for (int i = 0; i < dim; ++i) sum += v1[i] * v...
70,850,875
70,851,169
C++ OOP divide fractions
it is my first post here sorry if it is irrelevant I will delete it. I started learning C++, and I am currently learning OOP with OpenClassrooms. It asked us at some point to overload some operators on our own to go further... Here's the thing, I could do it, but I'm not sure to fully understand what happens(And I woul...
The operator overloads are regular functions with funky names, and they are used through a simple transformation. a / b is transformed into operator/(a, b), since operator/ is a free function. copy /= b is transformed into copy.operator/=(b), since operator/= is a member function. That's all there is to it. (As far as ...
70,851,009
70,851,231
I don't exactly understand why my while loop is not catching any of these conditions
I'm trying to output the input string in reverse and when the user inputs "done", "Done", or "d" it will stop. With this, the while loop does not catch any of these conditions to stop the loop. #include`<iostream> using namespace std; int main() { string userInput; int i; char output; getline(cin, userInp...
replace while (userInput != "done" || userInput != "Done" || userInput != "d") with while ( ! (userInput == "done" || userInput == "Done" || userInput == "d") )
70,851,015
70,851,199
`LL` vs `i64` suffix in C++ Visual Studio compiler
I'm trying to refactor an old C++ code. At some point I've something like: #if defined(WIN32) && !(defined(__CYGWIN__) || defined(__MINGW32__)) # define I64_CONST(X) X ## i64 #else # define I64_CONST(X) X ## LL #endif So for defining a 64-bit literal in the code there's something like: (uint32_t)((data_in >> 32) &...
Yes, long long is a new type since C++11 which contains at least 64 bits, so it can be used for your literals (unless the source code is using two's complement and the compiler is using one's complement/sign-magnitude then -263 won't fit) Another way is to use the INT64_C in <cstdint> which was also introduced in C++11...
70,852,103
70,852,688
Ambiguous overload error when using conversion function
I am trying to understand overloading resolution in C++ through the books listed here. One such example that i wrote to clear my concepts whose output i am unable to understand is given below. #include <iostream> struct Name { operator int() { std::cout<<"Name's int version called"<<std::endl; return...
Essentially, skipping over some stuff not relevant in this case, overload resolution is done to choose the user-defined conversion function to initialize the variable and (because there are no other differences between the conversion operators) the best viable one is chosen based on the rank of the standard conversion ...
70,852,472
70,852,666
How to deduce template type based on another template type
I have a templated class, whose type is to be determined by another sub templated constructor. template <typename V, typename I> class Text{ public: template <typename Container, typename V = typename Container::value_type, typename I = typename Container::size_type> Text(Container& c) {} }; So usage would...
Your probably want to write your own deduction guide: template <typename Container> Text(Container&) -> Text<typename Container::value_type, typename Container::size_type>; Demo
70,852,595
70,852,802
Making libcurl json post request in C/C++
I am writing a Qt application, and I have a button which is supposed to register a user. I'm using the following libraries: https://github.com/nlohmann/json <- for json serialization/deserialization libcurl My goal is to be able to make a post request to the following endpoint: http://localhost:8000/api/register It i...
The first error is in the line curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, sizeof(json_data.dump().c_str()));. sizeof does not do what you suppose it does. Yet another error is in the line curl_easy_setopt(curl, CURLOPT_POSTFIELDS, json_data.dump().c_str()); stores a pointer to an inside of a temporary data json_data...
70,852,892
70,853,152
Why does Incrementing a size_t default value giving garbage value?
Why does Incrementing a size_t default value giving garbage value? #include <iostream> using namespace std; struct Test { size_t a; size_t b; }; int main() { Test wrong; cout << (wrong.a) ++; cout << endl; cout << (wrong.b) ++; cout << endl; Test right {}; cout << (right.a) ++; cout << endl; ...
Why does Incrementing a size_t default value giving garbage value? You need to be very careful with your terminology. default has specific meaning in C++. In your first case, the size_t variables in wrong are NOT being given default values. You are incrementing uninitialized variables that have indeterminate values. ...
70,853,041
70,858,781
C++ - running on VS code with code runner
I am trying to compile and run C++ programs on VS code. I have my compiler set up, and I am trying to use the terminal for taking the user input. I tried to change the settings config for code runner by updating the "code-runner.runInTerminal": true After this, the terminal refuses to run the code. I understand the er...
Looks like you have not set up your terminal root. Essentially, the code runner will try to look for a terminal root in contexts like these, and thus if it does not get one, it misreads the input file's name when you execute it. Essentially, set the value for "code-runner".terminalRoot to "/" (without the quotes). Here...
70,853,587
70,853,674
How to deal with ctime includes within the scope of a class in CPP?
I want to use <ctime> inside the scope of a class in C++. However, whenever I try to compile the following class, I get the error: error: 'time' cannot be used as a function time_t now = time(0); I think it may be something related to the fact that I am trying to call that function inside of the Session class, b...
You declared a constructor parameter with the same name time as the function name: Session::Session(std::string language, time_t date, time_t time) ^ Within the constructor block scope, the parameter hides the function with the same name (and also the data mem...
70,853,598
70,853,848
Is this implementation of a graph effectively linear in the number of edges?
I have a class which resembles an adjacency matrix representation of a weighted, directed graph. Let's suppose the graph has n vertices. Here is how it works: At first, allocate n2 slots to hold integers (stored in a variable named graph), in the form of n arrays each having n integers. Assign weights to the edges, wh...
No it is not, unless you can prove that the way you allocate and deallocate the edges is independent from n, which based on your description is unlikely. Remember that Big O notation considers the worst case of your algorithm. Since you first allocate n^2 slots and then remove the non-existing edges, your algorithm run...
70,853,895
70,854,112
Can't use std::source_location in VS2019
Although I am using VS2019 with compiler flag /std:c++latest, but I am not able successfully include the header <source_location>. The following compile error appears: fatal error C1083: Cannot open include file: 'source_location': No such file or directory
Compiler support for C++20 - cppreference.com C++20 feature Paper(s) GCC libstdc++ Clang libc++ MSVC STL Apple Clang std::source_location P1208R6 11 19.29 (16.10)* Verified on godbolt
70,853,973
70,854,021
How to fix const char* must match previous return type error?
int plugin::feature(const InstanceInput &input) { auto parse_word=[](const string input_text){ string text = input_text; int i=text.find("%"); if(i!=-1){ return text.substr(0, i); } return ""; }; .... } I am in Clion and it displays an error message at...
Instead of: if(i!=-1){ return text.substr(0, i); } return ""; Try if(i!=-1){ return text.substr(0, i); } return std::string(); auto return type for your lamda has been determined as string in the first case, and as char* in the second, which is a...
70,854,041
70,893,591
Chromium Embedded Framework (CEF)- unresolved external symbol
Please tell me, I'm trying to figure out CEF in the simplest example. I downloaded precompiled CEF binaries for windows:https://cef-builds.spotifycdn.com/index.html There was an example inside - I launched and built it, compiled an exe file, it starts and works. 1.Now I have created a new project in VS2019 - connected ...
The function that you want to use is defined in the libcef.lib, so you need to include that one too. Also you will need the libcef_dll_wrapper. Both are used by the cef-examples too. Try to add them, and see if it loads then #pragma comment(lib,"libcef.lib") #pragma comment(lib,"libcef_dll_wrapper.lib")
70,854,987
70,855,291
Finding the max lengths of strings to format a table output
I want to find the max length of specific attributes from a vector of Person objects. Below is an example of a Person object: Person::Person(string first_name, string last_name, int the_age){ first = first_name; last = last_name; age = the_age; } I have a vector that stores Person objects, and I must p...
Your use of std::max_element() is wrong. It takes 2 iterators for input, which you are not providing to it. It would need to look more like this: auto max_name = max_element( people.begin(), people.end(), [](const Person &a, const Person &b){ return a.getFirstName().size() < b.getFirstName().size(); ...
70,855,214
70,855,271
Why is the c++ program not outputting the modified pointer-to-pointer variable results in the caller function?
I am developing a tic-tac-toe board game in c++ for learning purposes, and I am passing a char** to a function that assigns the given parameter an array of pointers which stores a players name. Upon variable assignment, I am able to print the results of the initialized variable in the function call to void initPlayerNa...
The pointer playerNames is set like this: char* names[2] = {p1, p2}; playerNames = names; However, when the function initPlayerNames() exits, names, p1and p2 are all destroyed and thus playerNames points at unallocated memory. Besides, playerNames itself in initPlayerNames() is a variable which is destroyed wh...
70,855,282
70,855,593
std::filesystem::recursive_directory_iterator with consistent path separation?
I just noticed that std::filesystem::recursive_directory_iterator uses different path separateors (i.e. / vs \) depending on whether it's on Windows or Linux, is there a way to make it return paths with '/' to make it consistent across systems? This is how I am getting the paths: for(auto& path: fs::recursive_directory...
So, your problem has nothing to do with recursive_directory_iterator, which iterates on directory_entry objects, not paths. Your confusion probably stems from the fact that directory entries are implicitly convertible to paths, so you can use them as such. Your problem is really about path::string(), which, as the docu...
70,855,489
70,855,563
c++ function call - pass by reference calls pointer method / pass by value calls referense method
A function call is made in the code. In the first function call a pass by reference is performed calling the pointer function. In the second function call a pass by value is performed where the reference function is called. Why is this so? #include <iostream> void f(int *p) { (*p)++; } void f(int &p) { p-=10; } int mai...
x is an int variable. &x is taking the address of x, yielding an int* pointer. f(&x) can't pass an int* pointer to an int& reference, but it can pass to an int* pointer, so it calls: void f(int*) f(x) can't pass an int variable to an int* pointer, but it can pass to an int& reference, so it calls: void f(int&)
70,855,685
70,904,033
compiler optimisations and threads
I have a program that performs a task in a thread and I wanted to have the option to terminate early with a key-press. Here is a MWE: #include <chrono> #include <iostream> #include <thread> int main(int argc, char *argv[]) { char endChar = 0;// endChar is only written by keyboard thread std::thread kbth([&endChar]...
OK, as comments below indicated threading issues @ François Andrieux I have "fixed" it using atomics with the code below: int main(int argc, char *argv[]) { std::atomic_char endChar{0}; std::thread kbth([&endChar]() { // this thread monitors the keyboard char buff = 0; std::cin >> buff; endChar = buff; ...
70,856,124
70,864,722
What is the most efficient (or just best practice) way to set up a function that returns a reference to an std:vector but sometimes a default empty?
Take the following function (which obviously doesn't compile). const std::vector<int>& getMyVector() { if (something) return std::vector<int>(); if (somethingElse) return m_myVector; return std::vector<int>(); } Assume that m_myVector is large or is otherwise not well suited to being retu...
Despite your hesitations, I recommend defining a static empty result vector wherever you have defined m_myVector. std::vector<int> m_myVector; static const std::vector<int> m_emptyResult; Your code can then both compile and avoid copies. const std::vector<int>& getMyVector() { if (something) r...
70,856,298
70,856,423
c++ passing template param by shared pointer
wanna ask one question: I have two classes A and B, few data types can only be defined in class B, but A as a higher level class also need use these data types defined in class B. So, I defined a template function in class A, named define_spline(), I can using robot_1 (i.e., class B) class's pointer to passing the type...
A2<rp1->sp_> a2(9,3); // error Template parameters are always types (until very recently, but this is not material right now). rt1->sp_ is not a type. It is a discrete object. If you look where it appears, struct sp is the type in question. And sp_ is an instance of that type. Types, and objects, are two completely di...
70,856,484
70,856,533
How to use find function on map/unordered_map in multi-thread programming
I read somewhere saying find() is not thread safe on STL map because when other thread is inserting to the map, the map itself is re-balancing, so find() may not return the proper iterator even the entry is indeed in the map. My observation tends to echo this. How about hash map (unordered_map)? I fear it may have the ...
None of the standard library containers are threadsafe. If you want to do this kind of thing, you must protect all accesses (both read and write) by a mutex.
70,856,516
70,856,702
Boolean check before variable declaration in if statement
I have this code: #include <iostream> int function() { return 2; } int main( void ) { int integer = 5; if (integer == 5 && int i = function()) { std::cout << "true\n"; } else { std::cout << "false\n"; } } It's giving an error: test.cpp: In function ‘int main()’: test.cpp:10:23: error: expected prim...
As an alternative to the other answers, since C++17 you can also declare a variable in the scope of the if in addition to the condition (rather than using a declaration directly in the condition): if(int i; integer == 5 && (i = function())) You might want to add an initializer to i for a default value.
70,856,563
70,856,902
Vscode g++ it isn't finding .cpp definition files
I'm trying to compile a c++ example with multiple .cpp and .hpp files, but g++ doesn't find any member function definition. main.cpp: #include <iostream> #include "Person.hpp" int main() { std::cout << "HELL!\n"; Person a{"Jiraya"}; std::cout << a.getName() << "\n"; a.setName("Niko"); a.do_sm...
In your tasks.json you are using the default ${file} which means compile only the active file and not all source files in your folder structure. The VSCode documentation explains how to fix this for the case of all source files in the same folder here: https://code.visualstudio.com/docs/cpp/config-linux#_modifying-task...
70,856,853
70,856,923
Is it allowed to extend the std::numbers namespace with new definitions?
I have several mathematical numeric constants defined in a large codebase. Several of which (but not all) are now duplicated in the new C++20 <numbers> header. I'd like to have them all in one place; is it allowed to extend the std::numbers header to include the ones not already defined?
is it allowed to extend the std::numbers header to include the ones not already defined? No, you may not add definitions to std namespace nor its subnamespaces (except for class template specialisations in cases where that isn't explicitly disallowed). You can instead have them all in one place in your own namespace ...
70,857,051
70,857,159
What does this char string related piece of C++ code do?
bool check(const char *text) { char c; while (c = *text++) { if ((c & 0x80) && ((*text) & 0x80)) { return true; } } return false; } What's 0x80 and the what does the whole mysterious function do?
Rewriting to be less compact: while (true) { char c = *text; text += 1; if (c == '\0') // at the end of string? return false; int temp1 = c & 0x80; // test MSB of c int temp2 = (*text) & 0x80; // test MSB of next character if (temp1 != 0 && temp2 != 0) // if both set th...
70,857,171
70,857,271
Why does my random function generate the same number every time I call it in a loop?
I have my random function generating a pseudo-random number in the range: double Utils::randomNumber(int min, int max) { assert(min < max); srand(time(nullptr)); return (max - min) * ((double)rand() / RAND_MAX) + min; } However, when I call it in a loop, I always get the very same number, although I seed ...
Seeding repeatedly with tight timings will generate the same initial result after-seed every time. If seeding once per process isn't an option due to caller locality, then you should provide an initial static-state instead. What may work for you is this: #include <random> double Utils::randomNumber(int min, int max) {...
70,857,479
70,857,514
How do you forward declare header files?
I'm trying to forward declare the header files #include<memory_resource> and #include<deque>. But the following doesn't seem to work. This is pseudo-code: A.hpp class memory_resource; class deque; class A { public: ... private: std::pmr::deque<index_t> tempQueue; } A.cpp #include<memory_resource> #include<de...
No, you cannot "forward declare header files". In order to define a member of a given type, that type must first be defined. You can achieve that by including the header that defines it. Since you define the class A in A.hpp and that class has a member of type std::pmr::deque<index_t>, you must include the definition o...
70,857,562
70,857,655
Is this good enough to check an ascii string?
bool is_ascii(const string &word) { if((unsigned char)(*word.c_str()) < 128){ return true } return false } I want to check whether a string is ascii string. I also saw such a function to detect whether a string is ascii chars or not: bool is_ascii(const string &str){ std::locale loc; f...
ASCII is a lot more than just alpha characters and spaces. If you want to accept all ASCII, just use your second example and change the if: if(str[i] < 0 || str[i] > 0x7f) return false;
70,857,634
70,858,614
Generating random number until they repeat in C/CPP
I have a problem with a program in C or CPP. I need to make a program that will generate a random nubers in range of 1-365, but when the program generates the same number as it allredy did, the program will write the count of numbers and repeat it self again 100 times. #include <stdio.h> #include <stdlib.h> #include <...
Based on what you want to do, this (not tested) code could give you into the right way: #include <stdio.h> #include <stdlib.h> #include <time.h> int main() { // declare the lower and upper limits of the rand numbers int lower = 1, upper = 365; // number of repetitions of the process. // this will rep...
70,857,644
70,857,746
Implicit conversion to templated struct?
template <typename T> struct Foo { T var; Foo (const T& val){ var = val; } }; template <typename T> void print(Foo<T> func){} int main() { Foo f=3; print(f); // Works print(3); // Doesn't work } f is a well defined instance of Foo, so obviously it works. But since 3 is convertible (implicitly, I be...
Template argument deduction won't consider implicit conversions. To get the desired call syntax, you could add an overload for print like this template <typename T> void print(T a) // selected if T is not a Foo specialization { print(Foo{a}); // call print with a Foo explicitly } If the argument to prin...
70,857,663
70,863,332
How to make a deep copy of an array of pointers
I am in the process of creating a chess engine and I am using a chess engine that can be found here for it's ChessBoard and Piece classes. as part of the engine I have to make a deep copy of an instance of the ChessBoard class and and I am having a great deal of difficulty doing this. I have tried editing the copy cons...
You are using runtime polymorphism for your pieces. I.e. you have a chess board of pointers to Piece, which can be of different types (Horse, Bishop and so on). And your problem is that, when you copy construct your chess board, you need to copy construct each piece, but you only hold a Piece* to a polymorphic object. ...
70,857,677
70,858,076
Is there a way to get ascii value of a string representing a special character?
I'm working on a compiler and I simply want to be able to read the literal '\n' as it's ascii value (10) in my language. But there are actually more escape sequence like \n and I don't want to attempt to account for all of them by myself when C++ already is fully capable of that. I basically need a way to take the arra...
So after Remy Lebeau's comment and a rethink i decided to write my own code to handle most of the functionality of the C/C++ compiler. Using the special characters table from here I decided to not implement special characters which are more than 1 character long because I'm lazy. That leaves \n \t \v \b \r \f \a \\ \? ...
70,857,964
70,858,061
Why does my code to USACO Silver Breed Counting not work?
This is my code: #include <bits/stdc++.h> using namespace std; int main() { freopen("bcount.in", "r", stdin); freopen("bcount.out", "w", stdout); int n, q; cin >> n >> q; vector<int> holsteins(n); vector<int> guernseys(n); vector<int> jerseys(n); for (int i = 0 ; i < n ; i++) { ...
There are multiple bugs in the shown code, assuming that it even compiles, because: #include <bits/stdc++.h> This is a non-standard header file. On some C++ compilers the shown code won't even compile. Assuming that the shown code compiles: cin >> n >> q; vector<int> holsteins(n); This input is not checked fo...
70,858,122
70,858,448
Cannot find c++ boost header files on Ubuntu 20.04 LTS using apt installation
I have just upgraded my server to ubuntu 20.04 LTS. I am now trying to various different code packages on it and receiving errors relating to the boost installation. Rather than building from source, I have installed boost 1.71.0 using apt: sudo apt-get install libboost-all-dev However, when I try and compile code I a...
Managed to resolve the issue. Turns out that because I had a previous boost installation from a manual installation (before I upgraded to 20.04 LTS) and had deleted those files manually, further re-installs via apt were not recreating the files in usr/include/, due to other packages relating to boost still installed in...
70,858,271
70,858,479
Is there a modern alternative to constructor chaining in C++?
I have a class Foo with 2 constructors, A and B. Constructor B contains some important setup code and should always be run when an object is instantiated. At the end of constructor A, I want to execute the important setup code that is inside B. Below is an example of the described setup which involves connecting to...
You could create a private function (or a free function with internal linkage) to initialize the parameters to your delegate constructor. For example: class Foo { private: Database connect_to_db(const std::string& db_path) { // Validation and retry logic } public: Foo(const std::string& db_path) ...
70,858,474
70,858,593
C++ No matching member function for call to 'erase'?
Alright, so I am building a game that requires that I am able to add and remove a *Fighter object. I first declare member variable fighter here std::vector<Fighter*> fighter; I then implement Add and Remove like this: void Game::AddFighter(Fighter* f) { fighter.push_back(f); } void Game::RemoveFighter(Fighter* f...
You need take the iterator returned by std::find() and pass it to vector::erase(), eg: void Game::RemoveFighter(Fighter* f) { auto iter = std::find(fighter.begin(), fighter.end(), f); if ( iter != fighter.end() ) { fighter.erase(iter); } } Alternatively: void Game::RemoveFighter(Fighter* f) { d...
70,858,604
70,858,696
Howto call c++ member function as async call from QML
I'm calling a Q_INVOKABLE member function from a QML. The GUI freezes until the function is fully executed. I've some network operations going on in the invokable function therefore I want to GUI to continue exec and don't block for function to be completed. QT documentation contains WorkerScript QML but that doesn't ...
The async model does not exist in qml, this is why workerscript has been added. To get a similar behavior on the c++ side, you would have to use QThread. To pass the results of your computation back to QML once the worker thread finish, you can, on the QML side, connect a callback to a given signal emitted by your clas...
70,858,735
70,881,749
Delegates - What's the difference between Add() and AddUObject()?
When binding a Multi Cast Delegate, what is the use differences between Add() and AddUObject()? I've been using AddUObject() on all of my bindings and they seems to work fine which has me wondering what the base Add() version is used for. Ive read the information on this page : Unreal Documentation - Multicast Delegate...
Add takes in an FDelegate. AddUObject is syntactic sugar for creating a templated delegate and binding it to the provided UObject, then calling Add with the created delegate. It is just this: template <typename UserClass, typename... VarTypes> inline FDelegateHandle AddUObject(const UserClass* InUserObject, typename TM...
70,859,082
72,334,487
How to set version of a Qt application (made by QtIF)?
Just noticed a File version (4.2.0.0) from a Qt application, when mouse goes over the file. However that seems to be the QtIF version, not my application version. How to set that (mouser over) version of a Qt application (made by QtIF)?
This may be considered the expected behavior (f.ex. when used as an online installer), as the installer is able to install multiple versions of your program and/or upgrade your installation once a new version of your software becomes available. So, the installer is not directly related to a specific version of your sof...
70,859,130
70,859,902
How to restore default setting in VS Code
I was playing with VS code settings (I wanted to explore VS Code) and suddenly the code editing got changed. Previously the code was more colourful and there were different colours for different keywords. Now my code is mostly white. Please help me to get back to default code formatting settings.
To revert the settings completely, open the settings JSON file by bringing up the command palette (Ctrl+Shift+P) and running the command Preferences: Open Settings (JSON). Delete everything in there and save the file. However, you might just have switched to a different theme by accident. To check that, open the theme ...
70,859,260
70,863,113
Passing vector by reference to another class/file
I have 2 sets of header+source files. One with the Main GUI class and the other with a Derived GUI class (Main window that opens a second window). In the Main class I have a vector of strings. I can pass that vector by reference by calling a function in the Derived class and pass it by reference. I can use and update t...
To derived class add one more pointer field: class DerivedFrame: public OtherFrame { ....... private: std::vector<wxString> * pvwsM3 = nullptr; ....... }; Modify PassVector() method to fill pointer: void DerivedFrame::PassVector(std::vector<wxString> & vwsM) { pvwsM3 = &vwsM; } Use pointe...
70,859,738
70,867,416
Writing a specific Clang-tidy check to avoid passing an expression into std::vector::reserve()
In our codebase, we always use std::vector::reserve() to achieve higher performance. Most of the time they work well. Also, sometimes we might pass an expression into the reserve() function. For example, const double length = GetLength(); const double step = GetStep(); v.reserve(static_cast<std::size_t>(length / step))...
First, you'll have to decide exactly what you want reported. For simplicity, I am interpreting your question as wanting to report any call to std::vector::reserve where the argument is not an identifier. Next, the core of any clang-tidy check is the AST matcher expression. The tool clang-query can be used to directly...
70,859,778
70,860,071
If we return address of local variable of function using pointer, do we need to delete the pointer after using that function or not?
If I don't use delete ptr at comment here in below code, then it causes a memory leak? int *create(){ int a; int *a_ptr{&a}; return a_ptr; } int main(){ int *ptr = {nullptr}; ptr = create(); //here return 0; }
Actually you return pointer to object that is destroyed after create function ends its execution. int a; is created on stack so a_ptr points to some place on stack. During return all objects on stack are destroyed and there is only a_ptr left there as value. No, you don't have memory leak but ptr in main() function is ...
70,859,955
70,861,779
some blank space remains in QVBoxLayout after hiding widgets (Qt)
There are hundreds of widgets in QVBoxLayout. I am hiding/showing them based on option menus. If I hide some of widgets, some blank space remains in QVBoxLayout and I dont want this unnecessary space. Adding spacer at bottom is not solving the issue. Same for setting margin spacing. Its like hidden widgets consume some...
Layouts have some default spacing between each child widget, defined by setSpacing(), setHorizontalSpacing(), setVerticalSpacing(). Even if you hide the child widget, the spacing around it remains visible. (Note: I think this is a bad design decision made by Qt developers, but we need to live with it.) You have basical...
70,860,100
70,860,344
Why am I not able to print the last character in below code?
I am trying to take sentence as an input from the user in the below code. eg. Input - 9 do or die #include<iostream> using namespace std; int main(){ int n; cout<<"Enter the length of the sentence: "; cin>>n; cin.ignore(); char array[n+1]; cin.getline(array,n); cin.ignore(); cout<<arra...
std::istream::getline(char* s, streamsize n): Extracts characters from the stream as unformatted input and stores them into s as a c-string. n is the maximum number of characters to write to s, including the terminating null character. If you want to read your 9 characters of the sentence, not only your buffer needs ...
70,860,830
70,860,903
C++ SImple Looping To Find Largest Number From Array
Hi I create some mini looping with arrays to find the largest number from array, but the result is a random numbers, here's my code int highest( int num1, int num2, int num3 ){ int bracket[] = {num1, num2, num3}; int result{0}; for ( int i = 0; i < sizeof(bracket); i++) { if ( bracket[i] > result ) { resu...
Length of the array is sizeof(bracket) / sizeof(*bracket)
70,860,980
70,861,714
Unable to overload operator using templates
I am trying to overload the + operator for a vector class. The vector class is able to specify the data type using templates. The + operator should be able to take two different vectors and create a new resulting one with the dominating data type. Currently my code looks like this: template<typename T> class Vector{ pr...
The problem is that when you instantiate say a Vector<int> and Vector<float>, then both of these are distinct types. Moreover, currently neither of them is allowed to access the internals of the other. To solve the mentioned error, you should add a friend declaration as shown below: template<typename T> class Vector{ p...
70,860,988
70,861,256
Cleanest way to avoid writing same condition twice
Lets say I have a loop that inputs a value from user, and if the value is equal to zero, it breaks. Is there a way to do this without writing the same condition twice? for example: int x; do { std::cin >> x; if (x) { //code } } while(x); What is the cleanest way to do this?
It's probably cleanest to write a little function to read the value, and return a boolean to indicate whether you read a non-zero value, then use that function: bool read(int &x) { std::cin >> x; return std::cin && (x != 0); } while (read(x)) { // code to process x }