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
67,849,370
67,849,445
I tried to define a dynamically growing array using typedef and it works up to 79 index, beyond that it doesnt, can someone sort this out?
Without giving an explicit size, it works up to index 79. It prints the value 200 at index 79, but when I increase the index by 1 that is 80, it prints nothing and program terminates. #include <iostream> using namespace std; typedef int list[]; int main() { list myList{}; myList[79]={200}; cout<<myList[79]; /...
First, try to do the following: list myList {}; cout << sizeof(myList) << endl; // Prints 0, since no elements // Note, the number does not signifies the number of elements, // it signifies the number of bytes. The int foo[] is not a dynamically growing array, it is legacy of C and is as primitive as it can be. When ...
67,849,768
67,850,549
Do clang sanitisers check for uninitialised memory?
I have a simple example: #include <stdio.h> int main() { unsigned long int a; printf("a = 0x%lx\n", a); return 0; } demo Clearly, this code has UB. But when I try to sanitise it with: clang -fsanitize=undefined -O0 -xc main.cpp && ./a.out it runs "fine". Is this behaviour expected? Should I be usin...
The issue here is that the standard library is not compiled with sanitiser enabled. And the uninitialised variable is referenced in printf. It's enough to read from this variable in the same function to trigger the sanitiser: #include <stdio.h> int main() { unsigned long int a; if (a == 42) { prin...
67,850,164
67,850,557
C++ not writing whole data to UART port
I have been testing UART communication in C++ with wiringPi. The problem: It seems that C++ isn't outputting whole data into the UART port /dev/ttyAMA0. Perhaps I'm doing it the wrong way? Investigations: Note : I am using minicom, minicom --baudrate 57600 --noinit --displayhex --device /dev/ttyAMA0 to check the receiv...
You can't use serialPuts to send the null terminator. As with all similar functions, it will stop when the null terminator is encountered in the string. In this case I think your best option is to add a function that uses the ordinary write function that is used internally by WiringPi's own functions. You could make a...
67,850,917
67,850,963
Cannot std::cout an implicitly converted std::string
I used to display an string by std::cout << str << std::endl, and thought an object implicitly convertabel to std::string can be also displayed in this way. However, I notice that I was wrong. I cannot std::cout an implicitly converted std::string until I overload operator << for std::string. The following code demonst...
What is the difference between STL's overloaded operator << and my own overloaded operator<< for std::string type? Your operator<< is non-template, while STL's one is template. Why I cannot display the implicitly converted std::string object x with std::cout(compile error)? Implicit conversion (from X to std::s...
67,851,026
67,851,084
How to turn a class into a template class without breaking existing client code (pre c++17)?
Can I turn a class into a template class without breaking user code? I am trying to change a class to accept template parameters, but at the same time, I would like to avoid breaking existing client code. In more detail, the existing codebase was class A{ // some code }; I turned this into the following: template <typ...
You can do what std::string does: template <typename T> class basic_A{ ... }; using A = basic_A<defaultType>;
67,851,331
67,851,413
Compiler errors using inheritance in C++
I'm a newbie in C++. I've written an example code that illustrates the problem and causes compiler errors. class Quantifier; class Node { public: virtual void Match(/* args */) = 0; }; class QuantifiableNode : public Node { public: virtual void SetQuantifier(Quantifier *quantifier) = 0; }; class NodeBase : p...
It seems you're not entirely familiar with diamond inheritance. QuantifiableNodeImpl has two Node sub-objects, one via NodeBase and one via QuantifiableNode. The second Node subobject lacks a QuantifiableNode::Match. It seems that this might not be intentional: is QuantifiableNode really supposed to be a Node in its ow...
67,851,343
67,852,985
Throwing an exception in a destructor and subsequent destructors
I did an experiment with throwing an exception from a destructor and got a result that I did not expect. See the code snippet: #include <iostream> #include <exception> class A { public: ~A() noexcept(false) { std::cout << "in ~A" << std::endl; //throw std::runtime_error("~A exception"); } ...
and then the exception is rethrown? No, it is not "rethrown". The destructors are being called as part of throwing (and catching) the exception. This is slightly a semantical difference, but an exception gets thrown only once, here, and the objects get destroyed as part of the exception getting thrown. Let's set asid...
67,852,038
67,852,299
Why not using std::move everything?
i don't undertstand fully this answer. Why we not all using type with std::move? Example; std::map<int, int> try; void foo(std::map<int, int>& try, int t1, int t2) { try.emplace(std::move(t1), std::move(t2)); } int main() { int k = 1; int v = 5; try.emplace(k , v); // emplace copies foo(try, k, v...
The reason for not always moving an object is that after moving an object, you don't have it anymore. void f() { Object o; o.stuff(); SomeFunctionTakingAReference(o); o.stuff(); // your o object is still usable SomeFunctionTakingAReference(std::move(o)); // Here your o object is not valid anymor...
67,852,242
67,852,572
Why does this selection sort code shows different output when running again as compared to first time
Firstly when I have code this program it was running perfectly but running it again, it is not showing expected output can someone tell what's wrong with it #include<bits/stdc++.h> using namespace std; int main(){ int n; cin >> n; int arr[n]; int loc,min; for (int i = 0; i < n; i++) { ...
Forgoing the fact that variable-length arrays are not part of standard C++ (and thus code tutorials that use them should be burned), the code has two main problems. On an already sorted sequence, the inner-most if body will never be entered, and therefore loc will never receive a determinate value. The swap is in the...
67,852,352
67,852,898
compilation error due to private variable declaration inehritance
I get the following error compiling the code below: Student.cpp:20:9: error: ‘std::string Student::name’ is private within this context 20 | name = _name; | ^~~~ Student.cpp:7:12: note: declared private here 7 | string name; #include <iostream> using namespace std; class Student { pri...
I had a hard time understanding public, private, and protected when I was learning object-oriented programming in C++, and thought that I would share a few thoughts to hopefully clear some of this up. First of all, public, private, and protected are used to determine the level of accessibility of a variable or method i...
67,852,360
67,852,530
Value of const char* returns empty after construction
Casting this Vector3 into a const char* has worked in implicit and explicit conversions, but hasn't when attempting to convert it at construction time. Only then does const char* 'v3pchar' return blank. Any thoughts? The full code is below. Thanks! #include <stdio.h> #include <iostream> #include <string> using namespa...
v3pchar = v3string.c_str(); The const char * pointer returned by c_str() is owned by its std::string, and is only valid until the std::string is modified, or it gets destroyed, whichever comes first. Capsule summary: as soon as v3string is modified or destroyed, v3pchar is no longer valid. const char* v3 = Vecto...
67,852,951
67,853,657
Boolean expression evaluator on struct members
Background I have a struct: struct event { uint16_t id; uint8_t type; std::string name; // many more fields (either string or integer types) }; A boolean expression(stored in a string): name = "xyz" and (id = 10 or type = 5) I have a vector of event objects(thousands) std::vector<event> and want to ch...
Build a map from field name to std::function<std::function<bool(event const&)>(std::string const&)>, like: lookup["name"]=[](auto str){ return [val=std::move(str)](auto& e){ return e.name==val; }; }; now you can convert your pairs into test functions. Now your name = "xyz" and (id = 10 or type = 5) becomes ...
67,852,966
67,853,014
Check what compiler flag is set within C++ code
Is there a way to check what flags are set on the compiler in running C++ code? Specifically, was this code compiled with /fp:precise or /fp:fast from within the program?
In the msvc documentation you can do this using predefined macros: https://learn.microsoft.com/en-us/cpp/preprocessor/predefined-macros?view=msvc-160 _M_FP_FAST Defined as 1 if the /fp:fast compiler option is set. Otherwise, undefined. _M_FP_PRECISE Defined as 1 if the /fp:precise compiler option is set. Otherwise, und...
67,853,256
67,853,752
Deep copy queue recursively C++ (Implemented using a doubly linked list)
I'm building a queue using a doubly linked list. I want my deep copy constructor to recursively deep copy the entire queue however I get a segmentation fault when I do the following: // Recursive helper method for deep copy constructor void queue::copyAllNodes(Node* og, Node *cpy) { if(og == nullptr) back = og; ...
First, understand you're not actually copying anything here. You're just enumerating by recursion and assigning pointers. At best that is a shallow copy; in reality your algorithm is completely broken. There are ways to copy a linked list recursively, including bidirectional linked lists. Whether it is wise to do so is...
67,854,068
67,854,208
Variadic constructor issue
I've been working on a project, but I got a weird error. I can't pass 2 Shader instances to a variadic constructor, even though it says it supports 2 Shader parameters. Exact error message: E0289 no instance of constructor "Program::Program" matches the argument list argument types are: (Shader, Shader) Here is code: #...
Your constructor is missing an argument list. It got a variadic template parameter, but an explicitly empty argument list. Apart from that, as @richardcritten mentioned, you didn't delegate the constructor as you intended, but would have created a temporary instance of Program instead. Delegate (by using initializer li...
67,854,320
67,854,445
Conversion between jboolean* and uint64_t*
I'm trying to convert a jbooleanArray with 128 elements (always) to a C++ array of bools with 128 elements also. extern "C" { JNIEXPORT jboolean Java_com_app_flutter_1app_JNI_loadBufferNative( JNIEnv *env, jbooleanArray jMidiNotes) { bool midiNotes[128] = {false}; *reinterpret_cast<uint64_t*>(midiNotes...
You can't do pointer arithmetic on object handles like that: *reinterpret_cast<uint64_t*>(midiNotes + 64) = *env->GetBooleanArrayElements(jMidiNotes + 64, nullptr); You should first get a pointer to the array elements using GetBooleanArrayElements and then do pointer arithmetic on that pointer. For instance, do like t...
67,854,357
67,926,315
storing integers in single value texture in opengl not working
I am trying to write a compute shader that works on a state. I want to store the initial value of this state in a single channel texture. However, this does not work. I have the following code: GLuint tex; glGenTextures(1, &tex); int time_horizon = 1000; std::vector<decltype(time_horizon)> tex_vals(width * height * 4,...
I will just put here the answer which was already provided in the question comments. glReadPixels reads pixels from the currently bound frame buffer. To read the pixels from a texture you should use either glGetTexImage or the more modern version glGetTextureImage (4.5), which allows passing texture handle directly wi...
67,854,366
67,854,556
How to properly use IoC container?
I'm very new to IoC idea and I'm trying to jump over the Service Locator pattern. I chose the Kangaru implementation. Suppose I want to use Audio and Logger services in different places of my app. What I have now: #include <kangaru/kangaru.hpp> #include <iostream> using namespace std; struct IAudio { ...
The main advantages of using a library to handle dependency injection is: The automation of boilerplate code Having a central place that contains the instance about the current context Using a dependency injection container, you have that single entity that contains the all the instances. It can be tempting to send t...
67,854,568
67,861,720
Wide char input stream std::wifstream is getting corrupt while deserializing object which was serialized using std::wofstream
I am trying to write my own custom serialize and de-serialize for an object of my application. I know there are plenty of libraries like boost serialize etc. available for ready use but I wanted to learn this serialize and de-serialize hence this effort. Problem occurs when I try to de-serialize(using std::wifstream) t...
I think I found the problem. The issue is, de-serialization using any std fstream when file is opened in binary mode CAN NOT be done using the extraction operator >>. Similar topic was discussed HERE. Please refer below code to see where the problem existed in the question code. class IArchive { std::wistream& mSt...
67,854,623
67,854,635
Read 4 bytes a time with ifstream from binary file
I have a binary file that contains floats so that every 4 bytes are a float. I'm not sure how I can read in a way that every four bytes would be stored as a float so I can do whatever I need with it. Here's my code: int main() { float i; std::ifstream inFile("bin_file", std::ios::binary); while (inFile >> i...
The operator>> in streams is designed for formatted data (i.e. strings). You want to use read instead: int main() { float i; std::ifstream inFile("bin_file", std::ios::binary); while(inFile.read(reinterpret_cast<char*>(&i), sizeof(i))) { std::cout << i; } inFile.close(); return 0; }
67,854,714
67,855,014
Reduction of search space in binary search
I am solving the classical binary search problem: class Solution { public: int search(vector<int>& nums, int target) { if(nums.empty()) return -1; int lo=0, hi=nums.size()-1; while(lo<hi) { int mid=lo+(hi-lo)/2; //if element found at position mid, return mid ...
I am seeking an intuitive explanation for setting hi=mid (specifically with the while loop condition as lo<hi and not lo<=hi). I think we should set it as hi=mid-1, since we know that mid cannot contain our answer (if it did, then we would have already returned). There are two main potential issues here: Correctness...
67,854,768
67,854,813
Difference between reference and regular variable in C++?
After you define a reference in C++, is there any difference between the reference and a normal variable? For example, after I define a reference in the following code: int x = 10; int& xRef = x; Is there any way to tell that xRef is a reference to an int, rather than just being a normal int? Is int& its own type?
Is there any way to tell that xRef is a reference to an int, rather than just being a normal int? You can use std::is_reference: #include <iostream> #include <type_traits> int main () { int i = 0; int& ri = i; if (std::is_reference <decltype (i)>::value) std::cout << "i is a reference\n"; ...
67,854,819
67,854,833
What does for(int i=0,u,v; ...) mean?
I was looking through some C++ code and I saw that the for loop was for(int i=0,u,v;i<M;++i). I understand most of the for-loop but I didn't understand the int i = 0, u, v. My question is: is this just a way of initialing u and v? What is the purpose of putting them there? I'm new to cpp so I'm not sure what this means...
Actually, u and v are uninitialised. They are declared, and exist for the duration of the for loop, as does i. They have type int. That said, I would not write code this way as I find it unnecessarily obscure. I would write (adding some spaces for legibility): for (int i = 0; i < M; ++i) { int u, v; ... } A...
67,854,822
67,854,863
'Filesystem' member not in 'std' namespace
I have some code intending to get the file size of a PNG image (from a different stack overflow post). #include <fstream> #include <cstring> #include <cstddef> #include <filesystem> const char* INPUT_FILENAME = "test.png"; using namespace std; int main() { std::ifstream file; size_t size = 0; std::cout ...
The error is saying that your compiler doesn't support std::filesystem. There IS such a thing as "std::filesystem" ... depending on your compiler. This link might help: https://stackoverflow.com/a/49192230/421195 CONFIG += c++17 can be used with Qt 5.12 and later. For Qt 5.11 and earlier, it is not a recognized QMake ...
67,855,389
67,855,639
What does this casting mean?
What does this piece of code mean? #define kb_Data \ (uint8_t)((volatile uint16_t*)0xF50010) I understand what a #define statement does, but what does it mean when it casts a uint16_t pointer to a uint8_t integer? This is meant to be an array of bytes, as can be seen in here, but I don't understand how an int can act ...
Taken as a complete expression it's nonsense. I just did some testing and on g++ and clang++ by default it's a compile error. On g++ with -fpermissive it compiles and produces the value 0x10. However macros are not necessarily complete expressions, they are text substitutions. As was pointed out by Ben Voigt in a comme...
67,855,515
67,855,529
Using char to access vector<int>
I'm working my way through the leetcode problems in C++ for practice. I'm at problem number 3. I don't quite understand why you can access vector using char datatype. For example: vector<int> chars(128); char c = 'a'; chars[c]++; The above code just means increment the vector at position 'a'??? by 1. I'm confused. Are...
Assuming your system is using ASCII or UTF-8 or something like that, 'a' == 97. So, this is equivalent to chars[97]++.
67,856,016
67,856,544
C++: Creating a "cost"/"distance" matrix from a vector of strings
I have been working on this problem for a few days and was hoping for some guidance. Let's say I have a string vector, 'myVec,' and it has been defined such that: (Please note, these are just the values "inside" the vector, I used the push_back function to define myVec to be as follows): myVec[0] = X Y 2 //There is a d...
Start by converting your myVec to some usable struct like struct edge { std::string from; std::string to; int dist; }; Then create a mapping from the string location names to indices. Eg first storing all possible locations in a std::set and then creating a std::map<std::string, int> l2i with that. Create ...
67,856,438
67,856,768
Designing file reader for multiple file formats/headers
I'm trying to design a Reader class, that would be able to read multiple file types (mostly binary representation of something). To get all the metadata from the file, it's going to use Header class which will somehow tell the Reader class size of the file header, (maybe through static field, idk) num bytes to read and...
Generally implementing a generic Reader class for binary formats can be quite challenging. Since some file formats have variable length headers I would suggest to put the reading of the header completely into the Header class. Something like: struct Header { virtual size_t parse(uint8_t* buf, size_t len) = 0; virtual...
67,856,457
67,877,092
Reading parquet file is slower in c++ than in python
I have written code to read the same parquet file using c++ and using python. The time taken to read the file is much less for python than in c++, but as generally we know, execution in c++ is faster than in python. I have attached the code here - #include <arrow/api.h> #include <parquet/arrow/reader.h> #include <arrow...
If you want a comparison try this CPP code: #include <cassert> #include <chrono> #include <cstdlib> #include <iostream> using namespace std::chrono; #include <arrow/api.h> #include <arrow/filesystem/api.h> #include <parquet/arrow/reader.h> using arrow::Result; using arrow::Status; namespace { Result<std::unique_pt...
67,856,615
67,856,977
Checking if the sums of the levels of a Binary Tree are equal
I'm trying to figure out a function in c++ to calculate the sums of all the levels of a binary tree and then checking if those sums are all equal, and returning TRUE if they are. So for example, if the first node is 10, the sum of its children has to be 10, and the sum of their children has to be 10, and so on... I'm h...
if you have defined the Node data as follows struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode() : val(0), left(nullptr), right(nullptr) {} TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), r...
67,856,732
67,857,483
Problems with swapping
I was solving a problem and the problem description was: Given a number N. You have to perform exactly two swap operations to make the number as large as possible. You are given a number N (10 ≤ N ≤ 2×109). You have to perform exactly two swap operation. You may choose any two unequal positions of this number, and swa...
As @molbdnilo mentioned, your ma variable is only a copy of your s[j] char. To actually switch between those two chars, you need to use a temp variable to store the location of j int jtmp; for(int j=i+1;j<s.size();j++) { if(ma < s[j]) { ma=s[j]; jtmp = j; } } Full modified code: #include <iostream...
67,856,951
67,858,346
Where is the const& args stored?
Here is the function definition const int& test_const_ref(const int& a) { return a; } and calling it from main int main() { auto& x = test_const_ref(1); printf("%d, %p\n", x, &x); } output as following ./debug/main >>> 1, 0x7ffee237285c and here is the disassembly code of test_const_ref test_const_ref(int con...
The code exhibits undefined behavior - the function test_const_ref returns a reference to a temporary, which lives until the end of the full-expression (the ;), and any dereference of it afterwards accesses a dangling reference. Appearing to work is a common manifestation of UB. The program is still wrong. With optimiz...
67,857,057
67,857,196
Program skipping first input after loop
I'm working on this code which is asking user to input data (student data). I made a constructor which is taking input of all fields on first run which goes fine on the first run. When I continue to go again via loop its skipping the Name input every time. Code #include<iostream> #include<fstream> #include<string> usi...
This is happening due to the fact that when you are reading choice using cin, then it will read the choice leaving the newline character behind. That’s why when you try to read name by getline() it reads endofline character (Due to this in the person.txt you will see there will be blank spaces in name part). So just us...
67,857,109
67,857,310
Print numbers in two threads
I want to print numbers from 0 to n in two threads. Even number in the first thread and odd numbers in the second. How can I print numbers with help of my code? Current output is AAAA_1 AAAA_2 I expect for input 7: 0 1 2 3 4 5 6 7 I created a class class PrintOrder { private: int limit_; mutex m_; conditi...
Any reference, be it read or write, of data considered part of the predicate of a conditional state must be protected by the mutex intended for that purpose. That means everywhere, including the test conditions of your while loops. Starting the threads is simple enough, just make sure you join them on destruction. The ...
67,857,370
67,858,494
Finding ratio of 2 numbers in C++
I'm currently learning C++ using PPP by Bjarne Stroustrup. There is a Practice question: Write a program that prompts the user to enter two integer values. Store these values in int variables named val1 and val2. Write your program to determine the smaller, larger, sum, difference, product, and ratio of these values a...
As @Dominique points out: You are working with the wrong algorithm: In order to find the ratio between two numbers a and b, you are doing: calculate a/b; do something with the result. This does not work, as computers don't understand rational numbers (in mathematics, 1/3 is different from 0.333333333, but for a comp...
67,857,649
67,857,733
C++ std::function causes segment faults
Could anyone tell me why below code will lead to a segment fault? And it's weird that calling function f3 is ok, but calling function f4 will lead to a segment fault. And if I use capture by reference in ComposableFunction, both f3 and f4 work fine... #include <functional> #include <iostream> using namespace std; tem...
This is a nice one. Your code captures *this by reference, and that reference quickly becomes dangling. if I use capture by reference in ComposableFunction, both f3 and f4 work fine That causes even more references to dangle, so it's not a solution. GCC warns about this with -Wall -Wextra, but doesn't explain it very...
67,857,974
67,858,063
Function pointer issue: How to provide pointer from non member function to member function
i need to do something like this ..., in a project of mine. class Alpha{ public: Alpha(void* p(int, int) = nullptr); void* calculatePointer; void test(); }; Alpha::Alpha(void* p(int, int)) : calculatePointer(p){}; Alpha::test(){ calculatePointer(5, 10); } vo...
If you're confused about the exact syntax of a function pointer it's probably best to define a type alias. If you use using, the "rhs" is <return type> (*)(<parameter types>) class Alpha{ public: using FunctionPtr = void (*)(int, int); Alpha(FunctionPtr p = nullptr) : calculatePointer(p) {} F...
67,858,389
67,858,515
Is GCC correct to ignore the nodiscard attribute on overridden member functions?
Due to this question and the answers, it's not 100% clear whether attributes are inherited or not, but probably they're not since it's not stated in the standard. That's why if we have only the declaration marked as nodiscard in the base class, and compile using Clang, we only get a warning if we access the object usin...
For me it seems a bug, because it works on Clang. But this bug needs 2 conditions to trigger: virtual method Indirect addressing. In your case, unique_ptr does it. If you get a simple instance and call function directly, you will see warning. But if you need a workaround, you can use another attribute. Here is a smal...
67,858,657
67,858,840
using reference pointer type as Paramter in c++
I faced some problem when i use Reference pointer type as parameter. first, this is my code. #include<iostream> using namespace std; void test(int*& ptr); int main(void) { int* ptr = new int[1]; ptr[0] = 100; cout << ptr[0]; test(ptr); cout << ptr[0] << '\t' << ptr[1]; } void test(int*& ptr) { int* tmp = new int[2]...
The reference isn't the problem. It's your dynamic memory management that is dreadfully broken. #include <iostream> using namespace std; void test(int *&ptr); int main(void) { int *ptr = new int[1]; // allocates a sequence of 1 ptr[0] = 100; cout << ptr[0]; test(ptr); // sends pointer to sequence by...
67,860,049
67,860,172
Why can't co_await return a string?
#include <coroutine> #include <string> template<typename T> struct Awaiter final { bool await_ready() const { return false; } void await_suspend(std::coroutine_handle<>) const {} T await_resume() const { return T{}; } }; struct ReturnObject { struct promise_type { ReturnObject get_return_obj...
This is a compiler bug in the implementation of coroutines in GCC, as there is nothing in the current drafts of the standard prohibiting custom/composite types for await_resume (as can be seen when replacing string with any user-defined type). The very same code for example compiles with the latest version of MSVC usin...
67,860,269
67,860,398
printing multiplication sign in c++
In Qt for setting the label of a button to be the "Multiplication sign" (not astrisk(*)) this is used : Button *myButton = new Button("\303\227"); I don't know anything about "\303\227". Also the code below will not print "Multiplication sign" : cout << "\303\227" ; I could not search for it cause I had no "keywords"...
those are called octal codes for UTF-8 characters, and I believe C++ has no useful native Unicode support. However, you may refer to this question for how to use unicode in qt. if you just want the multiplication symbol you may use this “×” U+00D7 or this U+2715 ✕
67,860,336
67,861,117
Use static property of a c++ class in qml
I have a c++ class like this: class MyClass : public QObject { Q_OBJECT Q_PROPERTY(QString P1 READ getP1) Q_PROPERTY(QString P2 READ getP2) public: inline explicit MyClass(QObject *parent = nullptr) : QObject(parent) {} inline static const QString P1 = "something1"; inline static const QString ...
As folibis pointed out, it seems that you are using MyClass as a QML singleton (qmlRegisterSingletonInstance or qmlRegisterSingletonType): // Does not need to be instantiated in QML (`MyClass` refers to registered singleton object) console.log(MyClass.prop) console.log(MyClass.getProp()) whereas you are registering it...
67,860,809
67,861,068
QLineEdit bug in access to its text
please guide me in finding the problem of this simplified code in reading text from qlineedit. My code exit in editUser->text() line. Every thing else is ok when I remove this line. #include ... QString USERID_LOG="SomeThing"; logDialog::logDialog(QWidget *parent) : QDialog(parent) , ui(new Ui::logDialog) { ...
Consider your constructor... logDialog::logDialog(QWidget *parent) : QDialog(parent) , ui(new Ui::logDialog) { ui->setupUi(this); QLineEdit* editUser= new QLineEdit( this ); QPushButton* okButton = new QPushButton(tr("OK")); connect(okButton, SIGNAL(clicked()), this,SLOT(okSlot())); ... } ...
67,860,922
67,860,956
Does variable shadowing work on all compilers in C++?
I ran this code on Leetcode.com but it prints random numbers. It works on my local machine, however. Anybody know if variable shadowing is supposed to work across all compilers? int carry = 0; if (1) { int carry = carry + 1; cout << carry << endl; }
The shadowing is defined by the C++ standard, and must work on all conforming compilers. Your code prints garbage, because carry in carry + 1 reads the new variable (which isn't initialized at that point yet, causing UB), not the old one.
67,861,507
67,862,034
Condition variable custom wait function
I created custom SpinLock class I want to use this class in condition variable, but have an error error: no matching function for call to ‘std::condition_variable::wait(std::unique_lock<Spinlock>&)’ cv_.wait(lk); I have error in line cv_.wait(lk); How can I support my SpinLock for condition variable?...
std::condition_variable only supports std::unique_lock<std::mutex>. Use std::condition_variable_any instead. The condition_variable_any class is a generalization of std::condition_variable. Whereas std::condition_variable works only on std::unique_lock<std::mutex>, condition_variable_any can operate on any lock that m...
67,861,902
67,861,982
How to use a c++ code in Flutter Desktop Application?
How to develop a custom plugin using C++ for desktop application and how to use C++ language in my Flutter code and how to access it. Is there any proper documentation for accessing C++ program in the dart language?
The best bet you have is using dart VM's FFI (foreign function interface) to bind to C APIs. You can mark functions in your C++ code to be "exported" to C as follows extern "C" void myExportedFunction() {} The extern "C" here prevents the compiler from mangling the function name while compilation. You can then compile...
67,862,158
67,862,266
C++ friend class circular include
I have this problem: I have class A which is friend with class B. The class A has a vector<B>. But I would like for the class B to be able to access the class A. class A { friend class B; static vector<B*> buffer; } Class B { public: B() { A::buffer.push_back(this); } } Is there some other way ho...
Your code is almost working. You need to forward declare B You need to use A::buffer.push_back(this); class B; // forward declaration class A { friend class B; public: static std::vector<B*> buffer; }; std::vector<B*> A::buffer{}; class B { friend class A; public: B(); }; B::B() { A::buffer.push_ba...
67,862,449
67,862,711
What does the C++20 standard say about usage of subojects as template non-type arguments?
The "Template non-type arguments" paragraph of the article „Template parameters and template arguments“ states: The only exceptions are that non-type template parameters of reference or pointer type and non-static data members of reference or pointer type in a non-type template parameter of class type and its subobjec...
The wording changed as part of P1907R1, which was adopted as part of C++20. Note that the first draft you cited - N4835 - predates this adoption (that draft was published Oct 2019, and this paper was adopted the following month at the Belfast meeting in Nov 2019). The closest draft to C++20 is N4861, which you can also...
67,862,539
67,865,700
Why using a different return type in virtual function declaration throws an error instead of resulting in a redefinition?
Base class: class Base { public: virtual int f() const { return 1; } }; Derived class: class Derived: public Base { public: void f() const {} }; Above code throws a "return type is not identical/covariant error". I've read few discussions on it. This one is similar ...
When the compiler encounters the matching signature (arguments, constness), it automatically makes the void f() const declaration virtual. So the definition of Derived is interpreted as: class Derived: public Base { public: virtual void f() const {} // virtual keyword is added }; It clearly looks like an a...
67,862,591
67,961,658
Google death tests without message
I am trying the Google Test framework on Linux and GCC10. Basic tests work fine, however there is something about death tests I don't get. Death test macros like EXPECT_DEBUG_DEATH have a second parameter ("matcher") which should be a regex string that is compared to whatever has been printed to stderr before the test ...
Turned out there have been two misunderstandings on my side: The matcher-strings are sub-string patterns. This means an empty matcher-string matches anything (not only empty messages as assumed by me). Actual msg did not really display an empty message string. It only uses a weird formatting. Google test adds a line b...
67,862,777
67,862,898
pthreads again: why does the for-loop inside my thread function generate overflow?
I use 4 threads and my code puts 4 threads to work on 1/4 quarter of 10000 ints and finds all the primes in that quarter. (i know its not a very smooth solution...) { ... for (int o{my_data->thread_id*2500}; o < (my_data->thread_id *2500) +2500; o++){ if (prime(o) == true) ss << o << "\n" ; ...
According to that error message, my_data->thread_id does not seem to have a value between 0 and NUM_THREADS - 1. It seems to have the value 1103437824. This is probably because my_data has become a dangling pointer, due to a race conditon. my_data points into the t_d array in the main thread. However, the lifetime of ...
67,862,810
67,863,456
Delete dynamically allocated memory after swapping its pointer
I'm relatively new to C++ and I want to understand memory management and pointers at the same time. Let's say I have the code below int* p1; int* p2; int* p3 = new int[some size]; p1 = p3; std::swap(p1,p2); How do I properly delete the dynamically allocated memory? Is doing delete[] p3 enough? Should I delete p2 too...
There is some fuzzyness in colloquial speech when you do something like this: delete x; We say "we delete x". Strictly speaking thats wrong, because what is deleted is the object pointed to by x. Every object allocated via new/new[] must be destroyed via one call to delete/delete[]. Whether you have two or more pointe...
67,863,254
67,863,478
Is Increment Speed Affected By Clock Rate
Consider the loop below. This is a simplified example of a problem I am trying to solve. I want to limit the number of times doSomething function is called in each second. Since the loop works very fast, I thought I could use a rate limiter. Let's assume that I have found an appropriate value by running it with differe...
If I understand the issue proberly, you could use a std::chrono::steady_clock that you just add a second to every time a second has passed. Example: #include <chrono> auto end_time = std::chrono::steady_clock::now(); while (true) { // only call doSomething once a second if(end_time < std::chrono::steady_clock...
67,863,591
67,863,632
What type is the next variable?
So I had this question at an exam. And I don't know which answer is correct. #include<bits/stdc++.h> using namespace std; struct Test{ int note; char exam[20]; }qwerty; int main() { cout<<qwerty.exam; } What is the type of qwerty.exam in the previous code? Is it char or char[20]? They said the right ...
But if the type is char[20], why can't I declare something like: char[20] exam; ? That's not the correct syntax. The correct syntax is char exam[20]. You could also do something like this: using char_array = char[20]; char_array exam; So I understand that the type does not depend on the number of elements. That's ...
67,863,916
67,863,974
Can't assign named pipe name to LPTSTR variable
I'm getting used to win32 API shenanigans but it's tiresome, the problem I face this time regards the assignemt of a name of a named pipe, this is what I'm doing: LPTSTR lpszPipename = TEXT("\\\\.\\pipe\\mynamedpipe"); This is verbatim from MSDN webpages, and surprise, surprise, this doesn't compile and issues the fo...
The problem is that, despite claims to the contrary, the examples given in the WinAPI documentation are written in (mostly) C, not C++. Also, the use of string literals to initialize non-const character pointers is no longer allowed in C++ (since C++11). So, replace: LPTSTR lpszPipename = TEXT("\\\\.\\pipe\\mynamedpipe...
67,863,989
67,864,056
Effectively getting items from map based on specific sort
I have a fairly easy problem: I have an std::map<int,T> and another std::set<int> (can be std::vector or similar too). In the map I store items, and in the other container I'm storing favorites (of the map). At some point, I'd need to retrieve (all) items from the map, but starting with the favorites defined by the oth...
Both std::map and std::set use the same strict weak ordering for ordering its contents. You can take advantage of this. You know that if you iterate over the map you will get the keys in the same order as they are in the set, therefore all it takes is a little bit of clever logic, something like: auto map_iter=myMap.be...
67,864,200
67,864,318
Print a matrix of alternating X's and O's given column and row constraints?
I'm trying to write an algorithm that prints a matrix of X's and O's, given the following params: int numRows int numCols int charsPerCol int charsPerRow e.g. calling printXOMatrix(int charsPerCol, int charsPerRow, int numCols, int numRows); with the parameters printXOMatrix(3,2,15,8); will result in the following b...
The problem is that you missed one case. You handled the case that the table switch up, with the condition: if (i % (numCols * charsPerRow) == 0), but you haven't handled the case when it doesn't . So I add another condition: if (i % (numCols * charsPerRow) == 0) { if ((numCols / charsPerCol)%2 == 1) { ...
67,864,713
67,872,512
Using boost::interprocess condition variable on an already locked mutex
I want to use boost::interprocess condition variable on an already locked mutex. I have locked the mutex already using mutex->lock(); function and because of this scoped_lock is not really appropriate for me. Is there any API available in boost::interprocess to wait on a condition variable without using scoped_lock? I ...
You need a BasicLockable. Indeed scoped_lock (or lock_guard) are not that. unique_lock and similar are: The class unique_lock meets the BasicLockable requirements. If Mutex meets the Lockable requirements, unique_lock also meets the Lockable requirements (ex.: can be used in std::lock); if Mutex meets the TimedLockabl...
67,865,145
67,865,481
std::variant of a container that contains itself
I have a binary format that I'm writing encoders and decoders for. Almost all of the binary types directly map to primitives, except for two container types, a list and a map type that can contain any of the other types in the format including themselves. These feel like they just want to be a typedef of std::variant t...
template<class...Ts> struct self_variant; template<class...Ts> using self_variant_base = std::variant< std::vector<Ts>..., std::vector<self_variant<Ts...>> >; template<class...Ts> struct self_variant: self_variant_base<Ts...> { using self_variant_base<Ts...>::self_variant_base; self_variant_base<T...
67,865,417
67,866,289
MAP_HUGE_1GB and MAP_HUGE_2MB missing?
I am on CentOS 7 with kernel version 3.10.0-1160.15.2.el7.x86_64. When I tried to use MAP_HUGE_1GB and MAP_HUGE_2MB flags, g++-9.3.1 complained: error: ‘MAP_HUGE_1GB’ was not declared in this scope; did you mean ‘MAP_HUGETLB’? Then, I found this post, the answer suggested that I need to "#define _GNU_SOURCE before #in...
Glibc doesn't define either MAP_HUGE_1GB or MAP_HUGE_2MB in any of its headers. If you have the kernel-headers package installed, you can get those constants by doing #include <linux/mman.h>. This isn't really ideal, though, so I'm not sure why glibc doesn't give you a better way to get them.
67,865,505
67,868,974
Are there any simple types sizeof(which) > 1 is guaranteed?
When writing generic code, I often want a simple type T for which sizeof(T) > 1 is guaranteed. For example: template <typename T> char test_foo(...); template <typename T, typename = std::enable_if_t<std::is_member_function_pointer_v<decltype(&T::foo)>>> ??? test_foo(int); template <typename T> struct has_foo : std...
When writing generic code, I often want a simple type T for which sizeof(T) > 1 is guaranteed. I think you do it the "wrong" way. For your example, you might directly use std::true_type/std::false_type. template <typename> std::false_type test_foo(...); template <typename T, std::enable_if_t<std::is_member_function_...
67,865,789
67,865,802
unexpected output of a program
I have written a basic program in C++ as below : #include <iostream> using namespace std; class asd { int a,b; public: asd(int a, int b): a(a),b(b){} void set(int a, int b) { a = a + a; b = b + b; } void show() { cout<<"a: "<<a<<" b :"<<b<<"\n"; } }; int main() { asd v(5,4); v.show()...
When you do a = a + a; in the set function, all three instances of a is the local argument varible a, and not the member variable a. A variable declared in a narrower scope hides variables of the same name in a wider scope. Here the narrow scope is the function and the wide scope is the object. To explicitly use the m...
67,866,010
67,866,096
new line character(enter key) in C++
I want to write a program to do a process after each sentences. like this: char letter; while(std::cin >> letter) { if(letter == '\n') { // here do the process and show the results. } } I want that when the user press the enter key (means that the sentences is finished) so that we do a process and then aft...
If I understand your question and you want to trap the '\n' character, then you need to use std::cin.get(letter) instead of std::cin >> letter; As explained in the comment, the >> operator will discard leading whitespace, so the '\n' left in stdin is ignored on your next loop iteration. std::cin.get() is a raw read and...
67,866,449
67,866,674
The clock in rostest does not appear to be running in simple test
I have built a very simple test, something like: #include <ros/node_handle.h> #include <gtest/gtest.h> struct SimpleTicker { SimpleTicker(ros::NodeHandle &nh) : _nh(nh) { _stateTickTimer = _nh.createTimer(ros::Duration(0.25f), &SimpleTicker::incrementVal, this, false, true); } void increment...
So it looks like the system is not spinning. I guess because of this specific way of running rostest the node, never calls to ros::spin() because it is busy running the tests. So wherever a sleep needs to occur, we need to spin instead, something like this: template <typename F> void spin_sleep(ros::Duration duration, ...
67,866,794
67,867,617
why do we iterate to root(n) to check if n is a perfect number
while checking if a number n is perfect or not why do we check till square root of (n)? also can some body explain the if conditions in the following loop for(int i=2;i<sqrt(n);i++) { if(n%i==0) { if(i==n/i) { sum+=i; //Initially ,sum=1 } else ...
It's pretty simple according to number theory: If N has a factor i, it'll also has a factor n/i (1) If we know all factors from 1 -> sqrt(n), the rest can be calculated by applying (1) So that's why you only have to check from 1 -> sqrt(n). However, you code didn't reach the clause i==n/i which is the same as i == sq...
67,866,808
67,867,369
Function works perfectly but changes value after return
I have a function to concatenate two LPCWSTRs together by converting them to wstrings, adding them, converting it back, and then returning that value (taken from: How to concatenate a LPCWSTR?) LPCWSTR addLPCWSTRs(LPCWSTR lpcwstr1, LPCWSTR lpcwstr2) { //Add the strings together std::wstring wstringCombined = st...
The issue is a misunderstanding of the lifetime of your memory. In your first example you have a dangling pointer: std::wstring combined = ... // Here you create the string (importantly, its memory) LPCWSTR lpcwstrCombined = wstringCombined.c_str(); // Make a pointer to the string return...
67,866,884
67,867,111
glsl vertex shader uniform variable not getting activated
I have been trying to pass a mat4 into VS. I am activating the shader program before passing the data: renderProg.use(); // glUseProgram( m_programHandle ); glm::mat4 mv = view * model; renderProg.setUniform("u_ModelViewMatrix", mv); renderProg.setUniform("u_MVP", projection * mv); But for some reason the uniform var...
The interface variabel Position is not used in the fragment shader. So the uniform variable u_ModelViewMatrix is not required. This uniform is "optimized out" by the linker and does not become an active program resource. Therefor you'll not get a uniform location for "u_ModelViewMatrix".
67,867,642
67,868,310
unique_ptr is not deleted after calling reset
This is my minimal, reproducible example #include <memory> #include <chrono> #include <thread> #include <iostream> #include <functional> class BaseClass { public: void do_func() { while(true) { std::cout << "doing stuff" << std::endl; std::this_thread::sleep_for(std::chrono::second...
The simplest way to synchronize these two threads would be to use std::atomic_bool #include <atomic> class BaseClass { public: std::atomic_bool shouldContinueWork = true; void do_func() { while(shouldContinueWork) { std::cout << "doing stuff" << std::endl; std::this_thread::sle...
67,867,691
67,867,754
C++ Inheritance (instantiating derived class inside base class)
class MainClass { string _ClassName; public: string MainClass(string _C) { _ClassName = _C; } SubClass s1; }; class SubClass : public MainClass { public: string Method_1() { return a; } string Method_2() { return a; } }; Why is SubClass s1 not wo...
The first problem is, that the MainClass does not know a thing about SubClass when you're trying to instantiate the object. You need to use a forward declaration and a pointer to make it work. Header file: class SubClass; //Forward declaration, allows pointer. class MainClass { string _ClassName; public: Mai...
67,868,070
67,868,238
Shifting char array right after "inserting" to a given position?
I've received a task, where I have to change every 5th character of a character array to = character and then shift the other elements of the array right, like this: I like fruit --> I lik=e fru=it. I have trouble with how to shift the elements after the = characters. I was considering something similar to simple sorti...
From running your code, it can be seen that the characters would be replaced, not inserted. Your code result: Input : I like fruit Output : I lik= fru=t A viable way is to input a std::string, use substr() to split the input into segments of 5, then adding a = afterward. The problem with using char[] is that it's of fi...
67,868,379
67,868,792
Tree Traversals with smart pointers
I have implemented a simple binary tree class in C++. have using smart pointers objects to hold the pointers to each node (shared for children and weak for parent). I was trying to implement a nested class for custom iterator (in-order, pre-order and post-order), but I couldn't figure out how to implement efficiently t...
You need to know which child each node is, and from that you can derive the next node from the structure. You can do that with pointer equality struct iter_base { std::shared_ptr<node> current; bool isRoot() const { return !current->_parent.lock(); } bool isLeft() const { auto parent = current->_parent.lock...
67,868,454
67,868,859
QQuickView shows an empty window when calling show
I am still trying to learn coding with QML + c++, so the very nature of this code snippet might sound a little bit unpractical. I am trying to write a class that inherits from QQuickView and loads a qml file. Here is my header file: #ifndef FORMLOGIN_H #define FORMLOGIN_H #include <QQuickView> class FormLogin:public...
Explanation The problem is caused because QQuickView expects an Item as root, not a Window. The problem is because QQuickView expects an element as root, not a window. Your program does the following: When you start the window that is visible is the QML Then the QQuickView window appears And after it hides the QQuickV...
67,868,721
67,868,854
Avoid multiple include from the same project
I have a project as it: main.cpp TaskManager.cpp Web.cpp (Use HTTPRequest.hpp LIB) I'm using main.cpp for simple web request, however TaskManager is really big in size, which is why it is in a different file. TaskManager need to send web request (like main.cpp does) but when I tried to use #include "Web.cpp" inside ...
When importing code from other file into a "main" file, we use something called a header file (.h). Never include a .cpp directly. For example, you have a file containing some function like this //test.cpp int add(int x, int y) { return x + y; } So you can create a header file called test.h: #ifndef TEST_H #define...
67,868,947
67,869,811
Check if wxUniChar is a digit
I have this condition: if (isdigit(exp.at(i))) Where exp is: wxString exp(MainText->GetValue()); The isdigit function causes the program to crash because I'm working with Unicode characters like √. Is there a function that does the same job but works with wxString and therefore Unicode characters?
There are wrappers for many CRT functions, and wxIsdigit is probably what you need.
67,869,476
67,869,544
unique_ptr is calling destructor twice
I have a block of code where I am using unique_ptr. class Abc { public: std::string msg; Abc(std::string m) { msg = m; std::cout << "Constructor: " << msg << std::endl; } ~Abc() { std::cout << "Destructor: " << msg << std::endl; } }; int main() { auto p = std::make_un...
You're constructing a temporary Abc (i.e. Abc(__func__)) firstly, then pass it to std::make_unique, which constructs the underlying Abc from the temporary (via the move constructor of Abc); i.e. two Abc objects are constructed, then destructor are called twice too. You can pass __func__ to std::make_unique directly, i....
67,870,095
67,934,813
send data beteen form qt5
I want to send data from from to another one I'm new in qt i googled my problem and find many solution but no one focused one qstring value login.cpp void Login::GetSerial() { QString s1 = cmd("WMIC cpu get ProcessorId"); s1 = s1.replace("ProcessorId",""); s1= s1.simplified(); s1.replace(" ",""); Q...
this is worked for me QString Seria; void Login::setLabelT(const QString& title) { ui->LblSn->setText(title); } void Login::GetSerial() { QString s1 = cmd("WMIC cpu get ProcessorId"); s1 = s1.replace("ProcessorId",""); s1= s1.simplified(); s1.replace(" ","");...
67,870,238
67,871,821
CMake: How can I check if a STATIC library has been compiled with -stdlib=libc++?
I want to check if all my dependencies are compiled using libc++ or not. If that's not the case, then return a warning or an error. Some of my dependencies are shared libraries and some are static. For a shared library I currently do like this if(MYLIB_FOUND) set (MYLIB_LIB "${MYLIB_LIBDIR}/lib${MYLIB_LIBRARIES}.so...
There is no need to check this for static libraries. Static libraries are just archives with object files and they have no runtime dependencies. They are linked directly to your final binary file. You should read more about how linker works: Stack overslow answer Wikipedia Youtube video If you compile your final bina...
67,870,250
67,870,329
How is printf printing 53 digits after decimal point?
I was trying to print the square root of a number at some given precision. int N; int precision; cin>>N>>precision; printf("%.*lf",precision,std::sqrt(N)); and this is what clang++ printed out: %./a.out 2 100 1.4142135623730951454746218587388284504413604736328125000000000000000000000000000000000000000000000000 It was...
Among the set of 64-bit floating-point values, sqrt(2) is closest to the floating-point value that exactly corresponds to the fraction 6369051672525773/4503599627370496. It's this rational number, or 1.4142135623730951454746218587388284504413604736328125 in decimal, that printf() is printing with as much precision as y...
67,870,327
67,870,388
How to enable automatic type deduction for class specific typedefs (c++17)?
I would like to deduce a class' (with default template parameter) typedef with c++17 automatically. Does somebody know if this is possible? The following code tries to illustrate this: #include <vector> template <typename T = int> struct A{ using Vec = std::vector<T>; }; int main() { A a{}; // works with c++ 1...
Is it possible to infer the type of Vec automatically without specifying the template type of A explicitly? Yes. You can leave the <> empty: A<>::Vec vec{}; Otherwise, A without <> or <int> etc., names a template with an unknown template type parameter, and you cannot use that to access nested identifier. What is t...
67,870,535
67,870,668
problem with compiling wstring on linux with cpprestsdk
I have code something like this using namespace web; using namespace http; const http_response& response = /*valid assignment*/ http_headers::const_iterator it = response.headers().find(L"SomeKey"); if (it != response.headers().end()) { //doing something } response is having valid d...
The project use wstring for windows, string for Linux. And they provide a type string_t and a macro U to help deal with this, your code needs to be changed to be compiled both on Windows and Linux. What is utility::string_t and the 'U' macro? The C++ REST SDK uses a different string type dependent on the platform bein...
67,871,126
67,871,190
Overloading function based on pointer type of unique_ptr parameter
I was under the impression that unique_ptr could infer class hierarchy in the same way that a normal pointer can, but when I try to overload a function like this: void func(unique_ptr<Derived1>& d1); void func(unique_ptr<Derived2>& d2); And then call one of the functions like this: unique_ptr<Base> b = make_unique<Der...
You are right that the implicit conversion operations of all standard smart pointers model those of raw pointers. This allows the second snippet to compile, i.e. unique_ptr<Base> create(){ return make_unique<Derived1>(); } However, there is a misconception about the first snippet, as there is never a builtin impli...
67,871,948
67,926,136
OpenGL generating multiple vao buffer
Are there critical performance differences between GLuint vao[2]; glGenVertexArrays(2, &vao); // and GLuint vao1[1], vao2[1]; glGenVertexArrays(1, &vao1); glGenVertexArrays(1, &vao2); I think of course latter one would have bad performance but due to my shallow understanding, I don't know how much would it be and wh...
You shound't imply those GLuint handles are stored in linear memory, and even if they are it doesn't mean the memory for objects those represent is continuous. It can be, or can be not during runtime, and it also depends on the access patterns you hint OpenGL when creating buffers. Graphic drivers do all that book keep...
67,871,955
67,872,198
How am I supposed to declare this C++ function?
I have a C++ program with an undefined reference error on the call of a method in a class. As near as I can tell, the method is public and I'm calling it with a parameter declared the same as the method definition, but eclipse/gcc tells me it is undefined. I'm not used to C++, can someone please tell me what's wrong wi...
You declare AttenuationConfigurationTable in the header file with the load_attenuation_calibration_table_from_flash function, but then the function with the same name in the implementation file is inside the definition for another class, Attenuation_configuration_table. Take the implementation for load_attenuation_cali...
67,872,058
67,872,572
How to use smart pointer from function that returns a raw pointer
I have a C++ library that I need to use which uses a build() function to return an object with new via a raw pointer. I want to use this object while using smart pointers but so far I have only found the solution to use smart_ptr.reset(build()) which works but is kind of ugly. Is there a better way of doing this or do ...
It depends. Consider this example: struct example { ~example() { std::cout << "bye\n"; } }; example* some_lib_function_A(){ return new example; } The library returns you a raw pointer to a dynamically allocated object. That's not nice, and to avoid dealing with the raw owning pointer you can wrap some_lib_fun...
67,872,111
67,872,155
How to close connection mysql, mysql.h in c++?
How to close connection in c++ when im using mysql.h library? MYSQL* conn; conn = mysql_init(0); conn = mysql_real_connect(conn, "localhost", "root", "admin", "uczelnia", 3306, NULL, 0);
To close your connection you would use mysql_close MYSQL* conn; conn = mysql_init(0); conn = mysql_real_connect(conn, "localhost", "root", "admin", "uczelnia", 3306, NULL, 0); mysql_close(conn); Description Closes a previously opened connection. mysql_close() also deallocates the connection handler pointed to by mysq...
67,872,173
67,873,098
How to convert the following C++ code to C#
1. sort(arr1.begin(), arr1.end(), [](Point2f lhs, Point2f rhs) { return lhs.x<rhs.x; } ); 2. sort(arr1.begin(), arr1.begin()+2, [](Point2f lhs, Point2f rhs) { return lhs.y<rhs.y; }); 3. sort(arr1.begin()+2, arr1.end(), [](Point2f lhs, Point2f rhs) { return lhs.y<rhs.y; }); I'm attempting to sort an array of p...
If you want to replicate the exact behavior you can use Array.Sort or List.Sort that takes a start and length of the range to sort. You will need to implement an IComparer<T> instead of using a delegate, but it is fairly trivial to make a implementation that takes a delegate to compare a property of the object. This sh...
67,872,425
67,874,260
Copy table from one database to another in multiple threads in C++
There is a huge SQL table in Postgres Database. I'd like to copy the contents of it to another different database (SQL Server) using C++. I have written a single-thread application and it works fine. I decided to use multiple threads to increase the performance of reading and writing data. Here in the code below I exec...
Start several threads or processes that each connect to both databases. Start a REPEATABLE READ READ ONLY transaction to the source database in each thread. Use the snapshot synchronization functions so that all sessions see the same snapshot of the source database and get consistent data. Have each session perform...
67,872,441
67,873,210
See SFINAE reason for a certain function
I'm using CLang. Is there a way for a certain function or whole .cpp to treat SFINAE as error? If there is an option --sfinae-as-error, or #pragma sfinae_disable/#pragma sfinae_enable for a certain function? It seems that due to SFINAE my function specialization has disappeared (became unusable) and I don't know how to...
Basically my build system just outputted last screen of errors, it truncated errors to last screen showing on console. Of cause in the beginning of screen it showed tiny message that truncation happened but I didn't noticed that. And when I restored whole log there appeared following lines: In file included from drafts...
67,872,555
67,909,117
Debugging Memory Mapped Files
I’m developing a .NET program which suppose to be communicate with other existing program in same machine using Shared Memory (Memory Mapped Files), The existing program itself include a native dll and .NET wrapper / bridge dll which I could consume to communicate with the other program. The thing is the other program ...
I'm not familiar with Memory Mapped File but if the two process share same memory, I believe it has same physical address, if this is true then you could probably use Cheat Engine with kernel mode. Just keep in mind that it can cause system instability or crash so make sure to save all your works before proceeding. You...
67,872,576
67,872,726
"pthread_join" doesn't return on a just cancelled thread (with "pthread_cancel")
I have a pool of threads (QueueWorkers class) in my program that are released using this logic: int QueueWorkers::stop() { for (unsigned int ix = 0; ix < threadIds.size(); ++ix) { pthread_cancel(threadIds[ix]); pthread_join(threadIds[ix], NULL); } return 0; } where threadIds is a class variable of typ...
Are sure the thread is in a cancelation or your thread cancelation_type is asynchronous? From man of pthread_cancel: A thread's cancellation type, determined by pthread_setcanceltype(3), may be either asynchronous or deferred (the default for new threads). Asynchronous cancelability means that the thread can be can...
67,872,602
67,923,961
Pass wchar_t instead of BSTR causes E_OUTOFMEMORY error
I have a simple DirectShow library and i also have a client application that call functions from that library. The problem is that some functions accept BSTR as arguments, but i prefer to pass either std::string or char*. It is certain that if i use one of these types i'll get plenty of compiler errors. I asked the rea...
If the method you are calling is declared as taking a BSTR parameter, then you must pass a real BSTR as the argument. There is no other choice. I’m sorry it’s not your preference. I agree there are all kinds of reasons why this is inconvenient. However trying to pass a wchar_t* instead of a BSTR is like trying to pass ...
67,872,610
67,874,084
How creating a multi-dimension array using std::array work?
Alright I've already watch Basic CPP online On Multi dimension array std::array<std::array<int,3>,3>arrayMD = {1,2,3,4,5,6,7,8,9}; This is CPP reference Documentation the first parameter is a datatype and the second param is size of the data template< class T, std::size_t N > struct array; Why can I pass an a...
Lets say you have an array like std::array<std::array<int, 3>, 2> arr; That would be an array of two elements. Each element would be an array of three int elements. It would look something like this: +-----------+-----------+-----------+-----------+-----------+-----------+ | arr[0][0] | arr[0][1] | arr[0][2] | arr[1]...
67,873,064
67,873,202
Check that element belongs to std::stack
I have a problem to write code / function that will check that number which provides user belongs to std::stack or not. I tried making it in different ways but I haven't found any working solutions. I tried: std::stack<int> myStack; const bool isInStack = myStack.find(userNumber) != myStack.end(); I tried also: std::...
As others have noted, a std::stack is probably not the best thing to be using, but assuming you have no other option then you'll have to go through the stack one by one and check each element: bool found_in_stack(int to_find, std::stack<int> stack) { while (!stack.empty()) { if (stack.top() == to_find) retu...
67,873,355
67,873,447
How to use cin after using system("pause")?
For a question, I must use Ctrl+Z to end reading parameters for an array. I search here for this problem and I write this code. My problem is, after Ctrl+Z, I can't cin some other variables and array. int main () { char a[51]; char b[21]; int n; for(int i=0;i<51;i++) a[i]=0; int ii=0; wh...
When you get an EOF, it gets remembered and won't even try to read anymore by default. Do std::cin.clear(); after the EOF to make it start trying to read again.
67,873,406
67,873,522
include a specific part of a header file in C++
I wonder if I can include a specific part of a header file instead of including whole of a header file! for Example in Python we can do that like: from math import sqrt which only import sqrt from math class. Is it anyway to do that in C++?
Kind of: extern "C" double sqrt(double); extern "C" int printf(char const*, ...); int main() { printf("sqrt(2) = %f\n", sqrt(2.0)); } Demo There is no way to do that for templates or class definitions though. There is also no way to do that for stuff in std namespace for many reasons, one of them being implementati...
67,873,610
67,873,837
Replace tabs in a string with several spaces
Can anyone suggest a good way to replace tabs in a std::string with multiple spaces such as " " (4 spaces)? I've attempted to use this code but this failed to replace them: std::regex_replace(cinput, std::regex("[ \t]"), " ");
Yes, you can use std::regex to do that: #include <iostream> #include <iterator> #include <regex> #include <string> int main() { std::string const text = "Quick\tbrown\tfox"; std::string output; std::regex const tab(R"(\t)"); std::regex_replace(back_inserter(output), begin(text), end(text), tab, ...
67,873,720
67,874,003
C++ Custom Exception classes
i am making a program and decided to make my own exceptions so i wrote the following header-only file: #ifndef ARGUMENT_EXCEPTIONS #define ARGUMENT_EXCEPTIONS #include <exception> namespace AAerr { class ArgumentException : public std::exception { private: const char* msg; static constexpr c...
I suspect that problem is in "main program", see OP comment in other answer: yeah i tried and it's the same thing. it doesn't work on my main program, but works fine on the testing program i have – user898238409 If "main program" is using dynamic libraries and exception are defined as "header only", this can lead to ...
67,873,819
67,873,995
What is this strange expression in GCC/Clang?
I have recently noticed an strange valid C/C++ expression in GCC/Clang which I have never seen before. Here is the example in C++, but similar expression works in C too: int main(){ int z = 5; auto x = ({z > 3 ? 3 : 2;}); // <-- expression std::cout << x; } What it does is somehow obvious, but I like to kn...
It's called statement expr, used in GCC. Your expression ({z > 3 ? 3 : 2;}) can be translated to if (z > 3) {x = 3;} else {x = 2;} From documentation: A compound statement enclosed in parentheses may appear as an expression in GNU C. This allows you to use loops, switches, and local variables within an expression. I...
67,873,850
67,877,301
How to use dlopen() to get the executables path
I am trying to use dlopen() and dlinfo() to get the path my executable. I am able to get the path to a .so by using the handle returned by dlopen() but when I use the handle returned by dlopen(NULL,RTLD_LAZY); then the path I get back is empty. void* executable_handle = dlopen(0, RTLD_LAZY); if (nullptr != executable_h...
Am I wrong in my assumption that the handle for the executable can be used in the dlinfo functions the same way a .so handle can be used? Yes, you are. The dynamic linker has no idea which file the main executable was loaded from. That's because the kernel performs all mmaps for the main executable, and only passes a...
67,873,911
67,873,980
is there a way to write a template function for dealing with smart pointer and regular pointer?
please i m trying to write a function that accept a vector of smart pointer or regular pointer but it never work, I want to write function getLargestRadius() that accept as argument std::vector<something*> or std::vector<std::shared_ptr<something>>. the only way it work for me is by overloading the function here is my ...
Without check, you might do, with template: template <typename T> int getLargestRadius(const std::vector<T>& v) { int largestRadius { 0 }; for (const auto& shapePtr : v) { if (const auto* circle = dynamic_cast<const Circle*>(&*shapePtr)) { largestRadius = std::max(largestRadius ...