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
64,747,864
64,747,947
How to use static_cast with a custom object?
I'm trying to use the static_cast that seems simple but I can't figure out what I'm doing wrong. I have the class Rat (used to represent rational numbers) and I want to cast it to a double. Then I could do double x = Rat(2,3) (it would store 2/3 into the x). To do that I need to do a static_cast so I tried double x = s...
You can only use static_cast if the type you cast and the one you cast to are related, or when the compiler knows how to perform that cast. Cannot convert Rat to double without a conversion operator Tells you that there is no conversion operator for Rat that allows the compiler to cast it to double. A conversion oper...
64,748,547
64,748,596
C++ "Too many initializers" Error while making an array of chars
I'm new to C++. I know a lot of python but I'm extremely new to C++. I was creating an array of chars but I got this error- "Too many Initializers" in VSCode. Please let me know how to fix it. Here's the code 1 | class Board { 2 | public: 3 | char pos_list[9]; 4 | 5 | void reset_pos() { 6 | pos_list...
EDIT: My initial answer was not correct, please find the modified correct way to do what you are looking for: You will not be able to use {'','',''} in order to assign empty values to all elements in the array in C++, you can only do that while initializing the array when you declare it. Also, it wouldn't be ideal beca...
64,748,723
64,754,361
Name resolution for function declared in anonymous struct
Should name resolution work for A, B, C in the following code in parameter list of f definition? namespace ns { struct A {}; struct S { struct B {}; struct { struct C {}; void f(A, B, C); } x; }; } #include <type_traits> void std::type_identity_t<decltype(ns::S::x)>::f(A, B, C) {} int...
[basic.lookup.unqual]/8 For the members of a class X, a name used ... in the definition of a class member outside of the definition of X, following the member's declarator-id(24), shall be declared in one of the following ways: ... (8.2) — shall be a member of class X ..., or (8.3) — if X is a nested class of class Y ...
64,748,807
64,750,476
WiFiClient.Read() returns number 1 for each character sent
I am trying to send data to an ESP32 using TCP. The program is written in the Arduino IDE. For sending the data I am using an app called Packet Sender. The program should print the data to Serial and also back to the WiFiClient. Whenever I send data to the ESP32 it prints '1' for each byte sent. The message "Received d...
while (ch = RemoteClient.read() != -1 ) is interpreted by the compiler as: ch = (RemoteClient.read() != -1) The right part evaluates to TRUE or FALSE, i.e. 1 or 0. The 1 for TRUE is what you are seeing being printed. You can add parentheses to make it do what you want: (ch = (RemoteClient.read()) != -1)
64,748,853
64,797,325
IFileDialog Overwrite File and Open Folder/File
I have two issues related to IFileSaveDialog & IFileOpenDialog I did not managed to find a solution for, I hope you can help me. When the user is saving a file with an existing name, the "Confirm Save As" prompt appears. I need the "Yes" option to be marked as default instead of "No". The User can open/load a file ...
When the user is saving a file with an existing name, the "Confirm Save As" prompt appears. I need the "Yes" option to be marked as default instead of "No". As @Remy Lebeau said that, you can use IFileDialogEvents::OnOverwrite method. And use MessageBox to create a suitable dialog. Some code: IFACEMETHODIMP OnOver...
64,749,047
64,752,060
Similar functionality to dup2 in boost
I would like to do some thing like this acceptSocket = accept(...); if (fork() == 0) { // .. dup2(acceptSocket, 1); dup2(acceptSocket, 2); execvp(/*some command*/); } Now I’m moving to C++ boost and I would like to do the same thing. Is there anything similar to this? Probably it would be Boost Process and ...
You can use Boost Process: https://www.boost.org/doc/libs/1_74_0/doc/html/boost/process/posix/fd.html This property lets you modify file-descriptors other than the standard ones (0,1,2). It provides the functions bind, which implements dup2 and close. So, example: #include <boost/process.hpp> namespace bp = boost::p...
64,749,259
64,749,586
How to use a discrete distribution as a class variable in C++
So I have a huge program (several .cpp files and .h) developed by someone else and I am trying to add some functionalities in just one of such files. I am new to C++ so it is hard for me. I want to use initialise a power-law distribution when initialising an "optimizer" and later sample from it when calling an "iterati...
Replace this line: std::discrete_distribution<int> power_dist(pmf.begin(),pmf.end()); with this: power_dist = std::discrete_distribution<int>(pmf.begin(),pmf.end()); Explanation: In the wrong version, you are creating a new local variable called power_dist who shadows the class variable this->power_dist, and using it...
64,749,666
64,750,081
Pointer error - "using uninitialized value" even though I think it is initialized?
I'm talking about this bit of code: #include <iostream> using namespace std; void citire(int& n, int* a) { cin >> n; a = new int[100]; for (int i = 0; i < n; i++) { cin >> a[i]; } } int main() { int n, *a; citire(n, a); for (int i = 0; i < n; i++) { cout << *a << "...
I fixed your code and also printed some addresses for your understanding. Old code: #include <iostream> using namespace std; void citire(int& n, int* a) { cin >> n; a = new int[100]; for (int i = 0; i < n; i++) { cin >> a[i]; } cout << "In citire Address of a = " << &a <<endl; cout...
64,750,084
64,750,263
Change object property
I have a class class Menu { public: vector<MenuItem> currentMenu; void init(); void show(); void trigger(); }; And class MenuItem { private: std::string text; Menu link; public: MenuItem(Menu &menu, string &text); string getText(); void onEnter(); }; In MenuItem constructor i...
class MenuItem { private: std::string text; Menu link; ... Your link variable is declared as an instance of Menu. The constructor, makes a copy of menu in link. Try to change Menu link with Menu& link MenuItem::MenuItem(Menu &menu, string &_text) : link(menu) , text(_text) {}
64,750,412
64,750,743
if counter is >9 then i want to print a letter equal to the counter in letter
I am making a nonogram but one requirement is that when a counter is bigger then 9 I want te print letters instead, so for example if the counter is 10 I want to print an A, 11-B, etc. this is the function I have, the value hulp is put in an array in a different function. int nono::letter(int counter){ char hulp; ...
you need to first subtract 10 from the counter before adding it to 'a' to make sure you are using the correct offset. and since you are already checking if the number us above 9 in the calling code, you don't need to do it here. So your code simplifies to the following: char nono::letter(int counter){ return 'A'+cou...
64,750,466
64,751,578
C++ Variable won't changed after declare in switch case
I am still learning C++. I want to write a code that default value is O and X. But user can change it by themselves, while two value cannot be the same and some special symbol. If there are any error, The value will reset to O and X. However, after reset the value in one of the switch case, the variable still contain t...
If I get your explanation of the problem right, the following should work. In this piece of code you create new temporary variables s1 and s2. if (!(s1.size() == 1) || (s1 == "+") || (s1 == "-") || (s1 == "|")) { string s1 = "O"; string s2 = "X"; ... Try to a...
64,752,070
64,752,516
Binary Search Tree- deleting a node causes other methods errors c++
I have a problem with deleting node from BST. I wrote a method that searches a node, that works fine, and when I'm trying to delete a leaf (an only case that I wrote so far) it causes an error (0xDDDD...) in printing methods. I assume that is because printing methods encounter some kind of null, but I have no idea how ...
Simple, you delete the node, but the parent of that node still points to it. So you are trying to print a deleted node. You have to remember who was the parent of the node you delete and to update it to no longer point to it. Many ways to do it, I personally would make tmp a double pointer if I was you but since your n...
64,752,314
64,753,064
C++ CUDA Thrust how to make an iterator that contains all even indices then all odd indices?
For example, if the array has 6 elements, this iterator would like like: [0, 2, 4, 1, 3, 5] I know about counting_iterator and constant_iterator, but how can I create the above iterator? I think it has something to do with transform_iterator, but I don't know how.
Here is one possible approach. You could use a permutation_iterator with a transform_iterator inside, something like this: $ cat t87.cu #include <thrust/iterator/permutation_iterator.h> #include <thrust/iterator/transform_iterator.h> #include <thrust/iterator/counting_iterator.h> #include <thrust/device_vector.h> #incl...
64,752,367
64,752,548
How does copy assignment work in for folly::Optional<T>?
I was reading the code in folly::Optional for copy assignment and I am not clear how exactly the call to construct() assigns a value to the optional. Specifically in construct() how does this expression work? new (const_cast<void*>(ptr)) Value(std::forward<Args>(args)...);
To deconstruct the line you wrote: std::forward<Args>(args)... is performing variadic-template perfect forwarding. In essence, it means that whatever was an r-value will be forwarded to, and so on, for any number of arguments. Value(std::forward<Args>(args)...) is calling the constructor of Value on these arguments. ne...
64,752,914
64,753,609
Smooth movement of player SFML
void update(RenderWindow& window) { if (Keyboard::isKeyPressed(Keyboard::W)) { dy = -0.3; } if (Keyboard::isKeyPressed(Keyboard::A)) { dx = -0.3; } if (Keyboard::isKeyPressed(Keyboard::S)) { dy = 0.3; } if (Keyboard::isKeyPressed(Keyboard::D)) { ...
In your code, the user input directly modifies the player position. This is probably the reason why the player movement looks so abrupt to you. Technically, in your code, the user input is what is determining the player velocity at any given moment. A more realistic approach would be to let the player have a velocity p...
64,753,313
64,753,499
openmp two consecutive loops, problem with reduction clause
There is two consecutive loops and there is a reduction clause in the second loop. #pragma opm parallel { #pragma omp for for (size_t i = 0; i < N; ++i) { } #pragma omp barrier #pragma omp for reduction(+ \ : sumj) for (size_t i = 0; i < N; ++i) { sumj = 0.0; ...
I'm not sure what you are trying to do, but it seems that something like this would do what you expect: #pragma omp parallel { #pragma omp for for (size_t i = 0; i < N; ++i) { } #pragma omp barrier #pragma omp for for (size_t i = 0; i < N; ++i) { double sumj = 0.0; ...
64,753,333
64,753,819
Why having jobs and waits for them in other thread cause whole application to wait?
I've got a thread pool struct ThreadPool { using Task = std::packaged_task<void()>; explicit ThreadPool(size_t workersCount) { workers.reserve(workersCount); for(uint32_t i = 0u; i < workersCount; ++i) { workers.emplace_back([=]() { while(true) { ...
First, your pool creates 4 working threads. Then, in main, you add some tasks into the pool queue, which call dss.DoSomething();. The workers then start executing these tasks. Inside, they first enqueue some more tasks, and then, they start waiting for their futures forever. These waits never end since there are no thr...
64,753,466
64,754,436
How do I automatically implicitly create a instance of a class at program launch?
I'm writing a Winsock wrapper library and I want to automatically call WSAStartup when the program runs and WSACleanup when the program exits. These two functions will be wrapped up in a class with constructor and destructor. The class will handle multiple instances etc. The first thing I thought of is using extern wra...
You could create a class to only do the initialization and deinitialization once and inherit from that class in your winsock classes. This does lazy initialization and avoids the risk of Static Initialization Order Fiasco. Example: #include <stdexcept> class WSA { struct Cleaner { // a class to just call WSACleanu...
64,753,508
64,753,887
c++ crosswise covariant: return type differs due to incomplete type
I am experimenting with covariance and came up with the following example that does at least not compile with clang 11 and on VS2015: class Number { public: virtual ~Number () = default; virtual Number const * increment()const = 0; }; class Even; class Odd : public Number { public: // error: increment() i...
While there may be workaround for what you're trying to achieve, the shown code is invalid. According to class.virtual#9: If the class type in the covariant return type of D​::​f differs from that of B​::​f, the class type in the return type of D​::​f shall be complete at the point of declaration of D​::​f or shall be...
64,753,668
64,753,843
min_element in template vector with comparator. Compile error
I have a template vector std::vector<T> beginStore; and I want to find minimum in that vector. So, first of all I implement it like this: template<typename T, typename Comp = DefaultComp> //some code T min = beginStore.at(0); size_t ind = 0; for (int i = 1; i < beginStore.size(); ++i) { if (Comp::compare(*beginStor...
DefaulComp::compare is template, so you cannot pass it that way to std::min_element. either provide type std::min_element(beginStore.begin(), beginStore.end(), &Comp::compare<int>); or wrap it in functor: std::min_element(beginStore.begin(), beginStore.end(), [](const auto& lhs, const...
64,753,805
64,754,191
C++ error C2676: binary '==': 'Person' does not define this operator or a conversion to a type acceptable to the predefined operator
I'm trying to remove objects from a vector while looping over it. I tried to implement "Erase-remove idiom" but still can't get it to work, I've made several re-writes to try make it work but still end up getting error. Here's the function meant to remove objects from the vector (parameter 1) void ta_bort_person(std::v...
This seems clumsy. I wrote the below to test something much cleaner. In short, I defined an operator== that compares against a string. #include <iostream> #include <vector> #include <string> class Person { public: std::string fnamn; std::string enamn; std::string nummer; }; bool operator==(const Person &p...
64,754,129
64,754,346
Can I use std::string_view with getline when parsing a file?
I recently learned about std::string_view and how it is much faster than allocating strings so I am trying to use this in place of std::string where possible. Is there a way of optimizing a loop that parses a file line by line to use std::string_view instead? This is the code I am working on. std::string line; ...
What you're looking for is mmap, that allows you to read into a file's data without copying them. Reading from a stream in C++ will always copy the data. You can then, of course, use std::string_view to point at the data revealed by mmap, and do all operations you like.
64,754,162
64,754,275
templated method with std::vector overload not taking hold
I know this question has been asked numerous times, but referring to the answer to this question: How can I specialize a template member function for std::vector<T> if I try a simple example of this using GCC9 it simply does not work, and I cant understand why not. Am I missing something here? #include <vector> #inclu...
Try changing: foo<std::vector<int>>( *( std::vector<int> * ) nullptr); to foo<int>( *( std::vector<int> * ) nullptr); Your top template expects a typename T and the method takes a vector of T.
64,754,562
64,754,671
why I can't cout after using string tokenizer
I am new to C++. While I was learning the strtok() function, I tried to cout after execution of the function, but I can't understand why the cout is not executing. #include<iostream> #include<cstring> #include<climits> #include<string> #include<algorithm> using namespace std; int main() { char s[100]="today is a ...
Sooner or later ptr=strtok(NULL," ") will return a null pointer. Which you immediately try to output leading to a null-pointer dereference and undefined behavior (and a very probable crash). I suggest you modify your loop to something like this: char *ptr = std::strtok(s, " "); while (ptr != nullptr) { std::cout <<...
64,754,867
64,757,742
Should function-try-block of d'tor allow handling of throwing member-variable d'tor?
I have a class whose destructor is noexcept(false). I know it only throws under certain circumstances, and I want to use it as a member variable of a class with a noexcept destructor. From https://en.cppreference.com/w/cpp/language/function-try-block I read "Every exception thrown from any statement in the function bod...
~NonThrowingDtor() noexcept try { x.willThrow = false; } catch (...) { // Ignore because we know it will never happen. } is "wrong" as equivalent to ~NonThrowingDtor() noexcept try { x.willThrow = false; } catch (...) { throw; } so simply ~NonThrowingDtor() noexcept { ...
64,755,303
64,755,526
How should I push the data in a vector into a map with integer key?
How should I push the data in a vector into a map with integer key such that I should be able to append to the existing vector at a particular key? #include <iostream> #include<map> #include<vector> using namespace std; int main() { std::map<int, std::vector<double>> my_map; std::vector<double> data; int j=0...
#include <iostream> #include <map> #include <vector> int main() { std::map<int, std::vector<double>> my_map; std::vector<double> data; int j = 0; data.push_back(1.0); data.push_back(3.4); for (int k = 0; k < 2; k++) my_map[j].push_back(data[k]); return 0; } EDIT: Simplified solution proposed. op...
64,755,561
64,757,078
A value of type const char* cannot be assigned to an entity of type char*?
I have a class like the following (I've deleted extraneous items): class GL_Texture { public: GL_Texture(); private: char* fileLocation; }; It's constructor looks like this: GL_Texture::GL_Texture() { fileLocation = ""; // error C2440: '=': cannot convert from 'const char [1]' to 'char *' } The construc...
You have a few choices: First, the one most people will agree is the best in most situations: don't use char *, use std::string. Second, initialize to nullptr instead. Third: fileLocation = strdup(""); and then clean it up in the destructor. This is ugly. Fourth: change it to char const *.
64,755,627
64,755,901
Calling a Void funtion inside a for-loop C++
This is my first post on StackOverflow! I'm having an issue with my project for my Intro C++ class. I get an E0349 error, "no operator matches these operands", on my call in the for-loop. I have looked at similar questions on here, but have found no solution. I apologize if I format anything wrong, or don't understand ...
You can't cout a method returning void. Moreover it's unnecessary in this case since the method itself call cout already. Just do : int main() { // Do "Press any key to continue..." on exit atexit([] {system("pause"); }); // Print out your name and course cout << "Jacob" << endl; cout << "ELET115N"...
64,755,708
64,755,837
Error getting output from mysql.h using C++ and g++
I have a small piece of code which (should) allows me to connect to an MySQL database, here is the code: #include <iostream> #include <mariadb/mysql.h> // /usr/includes/mariadb/mysql.h struct connection_details { const char *server, *user, *password, *database; }; MYSQL* mysql_connection_setup(struct connection_d...
The problem was how I was executing it, I had to use g++ connectdb.cpp -o output -L/usr/include/mariadb/mysql -lmariadbclient And not g++ connectdb.cpp -o output For future people with the same problem, here's a breakdown: g++ connectdb.cpp -o output (normal compile) -L/usr/include/mariadb/mysql (depending on what O...
64,756,098
64,765,711
static map not intialized correctly?
I'm using some c++ code in a static library in a macOS App. The c++ code contains the following: static map<char*, char*> aMap1; __attribute__((constructor)) static void initialize() { { static map<char*, char*> aMap2; printf("map1: %d, map2: %d\n", aMap1.begin() == aMap1.end(), aMap2.begin() == aMap2.end());...
someFunc was being called from an __attribute__((constructor)) function, so it was being called before the aMap1 initializer. To resolve the issue I moved the code to a dispatch block. The function could also be called from main instead of being marked as a constructor. static map<char*, char*> aMap1; __attribute__((c...
64,756,297
64,756,624
Read a 3x3 array from a text file into a 2d vector with correct format
file.txt 13 14 15 10 17 152 1 34 56 string line; ifstream infile("file.txt"); vector<vector<char> > num; while (getline(infile, line)) { vector<char> row; for (char &c : line) { if (c != ' ') { row.push_back(c); } } num.push_back(row); } for (vector<char> &row : num) { ...
Assuming you really want to store the numbers from the file, not the characters, I recommend you put each line into an std::istringstream and uses it to parse the numbers you would normally do from e.g. std::cin when you want to read plain int values. Perhaps something like this: std::vector<std::vector<int> > num; st...
64,756,444
64,756,750
Array initialization inside function
When I execute the following code it does its job well, but if I put the int a[16][16]; expression inside the main function , it just randomly outputs some number when executed. What is the cause? #include <iostream> using namespace std; int a[16][16]; int main(void){ for(int i = 1; i <= 15; i++) a[i]...
Static/global variables are zero initialized. In functions uninitialized variables stay aren't (zero) initialized. Reading uninitialized value is undefined behavior (UB). Running your code, we have: for (int i = 1; i != 16; ++i) a[i][0] = 1 a[1][1] = 1 a[2][1] = a[1][1] + a[1][0]; a[2][2] = a[1][2] + a[1][1]; // Access...
64,756,478
64,756,734
Create Queue from List C++
Pretty simple task, but I have some errors, which I don't understand. The task is to create a function, that will return Queue from List(using STL) Code: #include <iostream> #include <list> #include <queue> using namespace std; queue<int> reverse(const list<int>& data) noexcept { queue <int> Queue; for (list<i...
data is const list<int>&. You should use const_reverse_iterator. queue<int> reverse(const list<int>& data) noexcept { queue <int> Queue; for (list<int>::const_reverse_iterator i = data.crbegin(); i != data.crend(); i++) { Queue.push(*i); } return Queue; }
64,756,703
64,756,913
How to use structs, typedef, and template?
I'm trying to implement the following code, but I keep getting an error because of typedef, can someone please help? template<class T> struct box{ T data; box *link; }; typedef box* boxPtr; the error is: Use of class template 'box' requires template arguments
box is a class template. This means that it needs an argument whenever you instantiate it: box<int> integerBox; box<float> floatBox; // etc This is required anywhere you try to use a template class such as box. So a pointer to just a box doesn't make sense. It needs a type with it. For example: template <class type>...
64,756,869
64,757,484
Exception thrown: Read access violation when calling method front
When i try to take the first item from the queue, i have error. Exception thrown: Read access violation. ** std :: deque <int, std :: allocator > :: front ** (...) returned 0xDDDDDDE9. At the time of the error, the queue is not empty #include <iostream> #include <queue> #include <thread> #include<mutex> #include<chro...
You have a separate std::mutex for each thread which means effectively you have no mutex at all. You need to use the same mutex for both threads. You also have a typo in your pop function, it should be bool pop(int& x). You shouldn't really be calling mtx.lock() and mtx.unlock() directly, it is much better to make use ...
64,756,933
64,757,289
C++, function with changing amount of inputs (idk how to describe)
The funcion HIGHEST is all good and accepts variable number of arguments. The problem is how do I do variable amount of input? (idk what terms should be use to describe it, but examples should clear things up...) /*cout << highest(n, A[0],A[1],A[2],A[3]) <<endl; this is what I would like to achieve, but with a change -...
is there a specific reason you want the function Highest to get all array integers separately? Also - why did you choose to use an array instead of a vector? Assuming that you want to use an array, I'd suggest to change the function's arguments as follows: int highest (int num,int *arr); where arr is the name of your ...
64,756,949
64,757,039
Destructor runs with every method call of a class
I have a problem with my code. Every time a method like wypisz() is called, a destructor also runs every time and prints "us" on the screen. I want it only to be called when the program will end. I'm new to C++ and I don't know what I have done wrong. #include <iostream> #include <stdio.h> #include <vector> class Matr...
Why accepting argument by value cause the problem ? All objects with automatic storage are destroyed automatically. When you call a function with object parameters1, those objects are created at the beginning of the function call and destroyed when the function returns. When object is destroyed, the destructor is run...
64,757,113
64,757,336
I am getting a Double Multiplication error on this program
This problem is not working for a test case specified below. I think ther must be some errror in multiplication in the long double numbers #include<bits/stdc++.h> using namespace std; string multiplyStrings(string , string ); int main() { int t; cin>>t; while(t--) { string a; s...
Just use strNew << fixed; or strNew.setf(ios_base::fixed, ios_base::floatfield); before output. It helps show floating-point value as a decimal in any case.
64,757,182
64,758,285
Spring Kafka: C++ producer of reply for ReplyingKafkaTemplate
I use ReplyingKafkaTemplate to send a request to Kafka and receive the reply. Consumer of the request is a C++ program. After processing the request, its reply is produced by the C++ application. Now my problem is about format of the reply, because it seems that consumer of the reply in spring-side uses correlation Id ...
You need to echo back the correlationId header so the template knows which request this reply is for. Simply set the header on the reply in your C++ code to the value of the incoming request header.
64,757,225
64,762,185
Expand escape sequences detected by flex
In my scanner.lex file I have this: {Some rule that matches strings} return STRING; //STRING is enum in my c++ file I have this: if (yylex == STRING) { cout << "STRING: " << yytext << endl; Obviously with some logic to take the input from stdin. Now if this program gets the input "Hello\nWorld", my output is "S...
As @Some programmer dude mentions in a comment, there is an an example of how to do this using start conditions in the Flex documentation. That example puts the escaping rules into a separate start condition; each rule is implemented by appending the unescaped text to a buffer. And that's the way it's normally done. Of...
64,757,339
64,757,527
Unhandled exception thrown: write access violation: Printing out array elements
I have a function, which prints out an array of strings. The second function is supposed to print the reversed list but for some reason a new tab called xmemory pops up and I get the message: "Unhandled exception thrown: write access violation. this->_Myproxy was 0xCCCCCCCC." After hours of searching for this online, I...
Array index start from 0. It won't start from 1. So if you have array with 5 elements, you can access the first element by array[0]. array[1] represents second element. Your displayReverse() is trying to access 6th element in the array which doesn't exist. Below is the code with some modifications. #include <iostream> ...
64,757,430
64,757,608
Template Template Argument
I want to implement a function that shows different template classes that share the same characteristics (but are not necessarily in an inheritance relationship). I've written the following code below, but the compiler doesn't seem to be able to match the calling of show() to it's template. It says: string_int - "inva...
Your template template parameter in show is restricted to accept class templates that have exactly two template parameters. However, std::map has more than two template parameters, and hence the deduction fails. You can fix this by making the template parameters of the template template parameter variadic: template <cl...
64,757,489
64,758,006
C++ override understanding with different method's signatures
I expects that in c++ you can override method if it has same signature in Base and Derived classes including name, arguments and return type. If I try compile something like this I'll failure on both methods (get, get2) expectedly: #include <iostream> class A { public: A() {} virtual int get() { return 0; } virt...
If a base class declares a virtual function that returns a pointer or reference to a class, then overriding virtual functions can return a pointer or reference to a class type that derives from the base function's declared return type. This is known as "covariant return type". Example: class Object {}; class Derived : ...
64,757,556
64,759,378
Mutually exclusive slot allocator for threads using a vector of slots and mutexes in C++
If this has been posted anywhere else I am very sorry, but I could not find anything matching. In a class we have found a pre-designed slot allocator which stores a specified number of slots that can be acquired by threads. If a slot is required, the slot should work, else it is blocked until another thread releases. T...
std::vector<bool> is implemented effectively as a dynamic bitset. The exact way this is done is not specified by the standard, but will be implemented as a contiguous sequence of some integral type (e.g. std::uint32_t) where each bit represents a bool value in the vector. As a result, setting any one value to true or f...
64,757,965
64,758,022
Use of `= default` allowing private constructor to be accessed
I have the code: class Key { private: // If I use the = default keyword here, the line "Key a = {};" compiles // If I instead use Key() {}, that same line does not compile (as the constructor is private) Key() = default; Key(Key const &) = default; Key(Key &&) = default; Key & operator=(Key co...
When default constructor is defaulted, pre C++20, this code compiles, as your class with defaulted constructor is an aggregate, and you can initialize aggregates through aggregate initialization Key a = {}; // interpreted as aggregate initialization and bypasses access qualifier on constructor This code would not comp...
64,758,369
64,759,076
Getting path of system TEMP variable
I want to access the system TEMP variable in my C++ code. When I used getenv("TEMP") it gives the values of TEMP in user variable ("C:\Users\xxxx\AppData\Local\Temp\") and not system variable. Similarly GetTempPath also returns the C:\Users\xxxx\AppData\Local\Temp\ where as I want to have the path of the TEMP variable ...
The %USERPROFILE%\AppData\Local\Temp\ path IS the correct TEMP folder you should be using in most situations. That is the folder that APIs like getenv("%TEMP%"|"%TMP%") and GetTempPath() return on a per-user basis, by design. You should not be using the C:\Windows\Temp\ folder at all, as that is a system folder meant...
64,758,422
64,763,652
Launching an exe at the end of a Visual Studio Setup Project of a c++ Project
The only useful resource that describes how to launch an exe after the Visual Sutio Setup Project is finished is: https://www.codeproject.com/Articles/19560/Launching-Your-Application-After-Install-using-Vis. However, my project is written in c++ and I don't see how I can integrate the InstallerClass.cs which is a c# c...
I suggest that you could use InstallShield to realize the automatic operation of the program after installation. The method of implementation is: In the OnEnd() function of the InstallScript script, call the executable program. Note: The INSTALLDIR predefined variable stores the installation directory of the program. Y...
64,758,484
64,759,178
Connecting to Redis in Docker from Redis++
In my docker-compose file, redis is exposed at 6379, and reader is a gcc container. reader: build: context: ./reader-manager dockerfile: reader_manager.dockerfile volumes: - './reader-manager:/avn/reader-manager' depends_on: - redis redis: image: redis ports: ...
127.0.0.1 is a loop-back address. A loop-back address connects back to the container that makes the connection. If the C++ program runs in the reader container, then redis isn't running in the same container. You need to connect to the redis container: auto redis = Redis("tcp://redis:6379"); I wouldn't recommend hard...
64,758,699
64,760,824
Overloading of hidden friends by differences only in (mutually exclusive) requires-clauses: legal or an ODR-violation?
Consider the following class template, which contains two (hidden) friend declarations of the same friend (same function type; see below), which also defines the friend (and the friend is thus inline), but with the definition conditional on (mutually exclusive) requires-clauses: #include <iostream> struct Base {}; te...
From over#dcl-1, Two function declarations of the same name refer to the same function if they are in the same scope and have equivalent parameter declarations ([over.load]) and equivalent ([temp.over.link]) trailing requires-clauses, if any ([dcl.decl]). [Note 1: Since a constraint-expression is an unevaluated oper...
64,758,775
64,759,243
"result type must be constructible from value type of input range" when trying to push stack<unique_ptr> (or deque) into a vector
I essentially have something like this (I changed the variable names, sorry if it looks strange) #include <stack> #include <memory> #include <vector> struct Sequence { std::stack<std::unique_ptr<int>> numbers; // It works if I change it to this //std::stack<std::unique_ptr<int>, std::vector<std::unique_ptr...
This appears to be an instance of the old "move if noexcept" issue with std::vector. To be brief, std::vector<Sequence>::push_back may need to reallocate, and in such cases it will use the copy constructor of Sequence because it cannot prove that the move constructor will not throw an exception. In order to force it to...
64,759,497
64,771,843
How to make a class template that wraps a function in a noexcept-detectable, callable object, to use as a std::unique_ptr custom deleter?
Is it possible to use object type and free functions as parameters for creating custom deleters for std::unique_ptr ? I'm new to templates and came up till here: #include <memory> template<typename T, typename FreeFunc> struct ObjectDeleter { const FreeFunc &free_func; ObjectDeleter(const FreeFunc &free_func) : fr...
It's complaining because lambdas can't be used as template arguments (before C++20 anyway). Otherwise, lambdas are already callable objects that will not throw unless the function body throws, no wrapper class needed. You just have to do this awkwardness: auto myDeleter = [&x](Foo* v) { internal_foo_free(v); }; std::un...
64,759,518
64,777,412
Accessing begin and end in RcppParallel (exmaple calculating the mean of a vector)
I'm having a problem while trying to learn RcppParallel. I tried to modify the code form https://rcppcore.github.io/RcppParallel/ for the vector summation to calculate the mean of a vector instead, to see if I understand the general principle. My code is shown below. Using the function parallelVectorMean() on c(1,2,3,4...
Accessing begin and end is fine, but your operator function's logic isn't correct. Check this: void operator()(std::size_t begin, std::size_t end) { double temp_num = (double) end - (double) begin; double temp_value = (std::accumulate(input.begin() + begin, input.begin() + end, 0.0) / temp_num); va...
64,759,801
64,759,908
c++ array indexing with non-const value
I have the following code: DisplayObject conveyor_belts[] = {eggs_1, eggs_2, flour_1, flour_2, sugar_1, sugar_2, butter_1, butter_2}; std::thread conveyor_belts_t[4]; for (int j = 0; j < 4; j++) { conveyor_belts_t[j] = std::thread([&](){ conveyor_belts[j * 2].draw(15, 78 + i * 3); // segmentation fault her...
In your execution thread conveyor_belts[j * 2].draw(15, 78 + i * 3); C++ gives you no guarantee whatsoever that the new execution thread will execute this code and read the value j which was captured by reference before the original execution thread iterates the for loop and increments the value of j being referenced ...
64,760,248
64,760,364
OpenGL: Why can I not access the data in another frame?
I am using GLEW to create an OpenGL context and "standard" win32 to create the window. If I set up my VBO and VAO (both global variables) every frame then my geometry renders correctly. both program and positions are global and set before this loop happens. while (!done) { PeekMessage(&msg, hwnd, NULL, ...
glVertexArrayVertexBuffer binds a buffer to the vertex buffer binding point, but not to an attribute index. The assocaition between the binding point and the attribute index is established by glVertexAttribBinding: glVertexAttribBinding(0, vao); glVertexAttribBinding(0, 0); Respectively the DSA version: glVertexArrayA...
64,760,251
64,761,068
templates, forward declaration, dll
This is about the following setup of an application that uses (abstract) functionality from a *.dll and a static library and which causes read access violation at last (further details are provided below the code): ... static library ... // InterfaceWrap.h //----------- // dummy include #include <SomeTClass.h> templ...
Why not use real interface and DIP: struct IAnyAction { virtual ~IAnyAction() = default; virtual void AnyAction() = 0; }; class Proc { std::shared_ptr<IAnyAction> m_interface; public: Proc(std::shared_ptr<IAnyAction> anyAction) : m_interface(anyAction) {} IAnyAction* GetPtr() { return m_interface....
64,760,286
64,772,489
(non-boost) ASIO `Operation aborted` error
I am just learning asio, this is the minimal reproducible example of an error that I have encountered. The error is Operation aborted (code 125). I have absolutely no idea as to why this happens. Thanks for any help. #include <asio.hpp> #include <asio/ip/tcp.hpp> #include <iostream> #include <memory> class connection :...
A fundamental property of ASIO is that I/O objects must out-live their asynchronous operations. The destructor of I/O objects cancel outstanding asynchronous operaitons. In start(), a resolver is created and an asynchronous resolve operation is initiated. Then, immediately, the resolver is destructed, which cancels the...
64,760,651
64,760,750
How to pass an array of constexpr strings as an argument?
I have a file which contains arrays of strings representing some icons. static constexpr char icons1[2][40] = { "icon1_A", "icon1_B" }; static constexpr char icons2[3][30] = { "icon22_A", "icon2_B", "icons2_C" }; Then I have a class that wants to be initialized with a reference to these icons. class Display { pub...
The declaration here is needlessly complicated. Try and keep it simple: static const char* icons1[] = { "icon1_A", "icon1_B" }; If you're passing these in as arguments and you need to know exactly how many there are it helps to have some kind of terminator: static const char* icons1[] = { "icon1_A", "icon1_B", nul...
64,760,905
64,761,050
==20556== 16 bytes in 1 blocks are definitely lost in loss record 1 of 1
I am almost done writing a bunch of functions for a linked list class I created but for some reason I have one memory leak that stems from the append->insert_back->insert function. Attached is the code for each: append: void LinkedList<T>::append(const LinkedList<T> &l2) { if (l2.isEmpty()) { return; ...
You are allocating an LLNode<T> and assigning it to tmp. Then tmp is assigned to pos. What happened to newly allocated LLNode<T>? It is leaked.
64,760,973
64,761,174
How else can I access a bit field members?
So I understand that you can't have pointers to bit-fields because the pointers can only distinguish addresses to the byte level, not bit level. References to bit-fields are also not allowed. Are there any other ways that I would be able to reference the members of the bit field indirectly? Ideally I would be able to a...
You could use an array of function pointers that are initialized by lambdas to access each element of the bitfield with the different functions. class myClass { public: myStruct s1; static constexpr unsigned short (*accessors)(myStruct const &s)[] = { +[](myStruct const &s) -> unsigned short { return s....
64,761,140
64,761,196
Read from a socket without knowing the size of the buffer
I've added a delimiter to the end of all of my messages, so I know when I have reached the end of a message. Once my message exceeds the specified size of the buffer, and I have to read from the socket a second time, weird stuff happens. For example a random '\n' character will appear out of nowhere somewhere random in...
There's a number of problems here, but most important is you disregard how many bytes were read. You must pay attention to this and use it when constructing the string: std::string(buffer, valread); If you disregard this then you're passing in what's presumed to be a NUL-terminated C string, but instead you just have ...
64,761,448
64,761,480
Reference variable assignment logic
Okay, so I'm making a function that reduces a rational number by calculating the greatest common factor, and then returns the new numerator and denominator after reducing/simplifying. Ex: 24/60 to 2/5. void reduce(int &num, int &den){ int remainder = num % den; while(remainder!=0){ num = den; den = remaind...
You are changing num and den inside while loop. That value should not be changed. Please store num and den variables inside other variable and do the operation using those values as follows. void reduce(int &num, int &den){ int remainder = num % den; int tempNum = num, tempDen = den; while(remainder != 0){ t...
64,761,481
64,762,334
What kind of graph I need for Dijkstra's algorithm? C++
I am trying to learn some more stuff about graphs and Dijkstra's Algorithm, so I have a function that randomly generates a weighted undirected graph, saves in a file like this: numbers_of_vertices number_of_nodes node_a node_b distance_from_a_to_b etc. And then I run Dijkstra's to output the distances from node 0 to a...
Dijkstra's algorithm is a variation of a BFS traversal. The difference is, it utilizes a min heap to traverse to the closest node every time. Your function that randomly generates a weighted undirected graph should not create a pair of nodes where node_a and node_b have a distance of 0. This means the node is in the sa...
64,761,625
64,761,701
Function template taking a container type and a compare type
Below is some code that I would like to: take a container take a type return a new container of the same type containing objects (ptrs) from the original container that don't match the type of the compare type #include <typeinfo> // Algorithm wrapper around find_if that takes an STL collection and returns // the sub...
No need of template template parameter, just use typename TContainer: You might change order of template parameter to avoid to provide deducible types. You might use regular functor to simulate generic lambda (and so avoid to provide extra type), or use value_type from container. C++11 introduces std::copy_if. template...
64,762,278
64,763,083
decltype(fun()) for consteval methods
Consider the following code. I can compile it with GCC 10.2.0 and Clang 11.0.0 (as expected): #include <iostream> template<int> struct T { static constexpr auto fun() noexcept { return 0; } using type = std::remove_cvref_t<decltype(fun())>; }; int main() { decltype(T<1>::fun()) a = 1; std::cout << a; }...
As already said in comments to question, this is CLang bug. This bug appears only if a function is a static method, if it is a global function then code works (see working online example here). Hence one way to fix this is to use global function to forward result of static method. I did a bit more advanced example of s...
64,762,329
64,762,492
How does Visual Studio compile together multiple C++ files?
I have a simple project in visual studio with main.cpp, Log.cpp, and Log.h. main.cpp: #include <iostream> #include "Log.h" int main() { Log("Hello World"); std::cin.get(); } Log.cpp #include <iostream> #include "Log.h" void Log(std::string message) { std::cout << message << std::endl; } void InitLog() {...
This is known as the process of linking. The compiler needs to know the return types and signatures of the functions in the Log class (which is why you include the header), but it wont throw errors if it doesn't find the function definitions. When it compiles the cpp files into object code files, it basically leaves "h...
64,762,359
64,762,452
Using pointers to read and write to a file
I am new to pointers and I have a task to read a 2d array from a file. I have to use the function which takes in a parameter (char * path).As you can see i am manually typing in which text file i want to open in the code but i think i have to use pointers as it is the parameter in my 'read_from_file' function. I am tak...
If you don't want anything fancy: // Note: argv[0] is the name of the program itself, 1..n are actual arguments for (int i = 1; i < argc; ++i) { read_from_file(argv[i]); } Then you can use that in your function: std::ifstream infile(path); Typically in C++ you should specify arguments like this as const char*.
64,762,476
64,762,776
g++ inline assembly mismatch in brackets
g++ is complaining to me about a missing bracket in the following code: 1 2 3 v v v __asm__ volatile("inb %1, %0" : : "=a" (result) : "Nd" (portnumber) ); ^ ...
You have an extra : before the output, so you ended up with your output declaration in the input part. And the reason for that error: your input operand declaration where the compiler expects the clobber list. The clobber list can only include string literals (register names and "memory" and/or "cc"1), not (). __...
64,762,884
65,471,092
call boost signals2 slot on a separate thread
How can one call a boost signals2 slot on a separate thread without blocking the thread that is emitting the signal? I would like to get the functionality of the Qt5 QObject::connect with the QueuedConnection argument; for Qt5 details see Threads and QObjects. That is, I need to be able to emit a boost signals2 signal ...
boost::signals2::signal invoke slots sequentially on the thread that emits the signal. If you wish to achieve a non blocking behavior you would simply have to emit the signal on a different thread yourself. From what I understand, Qt QueuedConnection not only means the slot is invoked asynchronously, but on the receive...
64,763,372
64,763,465
How can I make a while loop keep incrementing while ascending
int range; int i = 1; cout << "Enter number range:"; cin >> range; while (i <= range){ cout << i << endl; ++i; What I have in mind Enter number range: 5 1 1 2 1 2 3 1 2 3 4 1 2 3 4 5
If you observer carefully, this will be solved using 2 loops instead of 1. int range = 5; for (int i=1;i<=range;i++){ for(int j=1;j<i+1;j++){ cout<<j<<" "; } cout<<"\n";
64,763,456
64,763,583
Not getting expected output as per Fermat's little theorem
According to Fermat's little theorem the modulo multiplicative inverse of a number can be found as below a^(m-2) mod m if a and m are co-prime. But I am not getting expected output in below program. Which is the wrong step in procedure? int pow_mod(int base,int pow,int MOD){ long long int res = 1; while(po...
base = (base*base)%MOD; All operands in the above are int so the calculation is done in integers. But (assuming 32-bit integers) the product base * base eventually overflows the int range during the loop. The following cast is one way to force the calculation to use long long int and produces the correct result. ba...
64,763,505
64,946,759
How to include .NET Core in my installers (Windows and macOS)
I have a C++ application that relies on .NET Core to interact with a C# assembly. I want my application to work without the need to install other components first, so I want to include .NET Core in my installers. There are scripts provided by Microsoft but they're intended for CI (they perform a non-admin installation)...
I've finally solved it by using the installers provided by Microsoft. macOS Included the .NET Core pkg as a "Resource" in the Packages project, then created a post-install script to execute it: #!/bin/sh sudo installer -pkg dotnet-runtime-3.1.10-osx-x64.pkg -target / In this case, .NET Core will be installed silently....
64,763,654
64,763,698
Is it right to use static_cast<void> to ignore iterator as return value?
I have to handle the [[nodiscard]] warning from std::remove; static_cast<void>(std::remove(stringVar.begin(), stringVar.end(), ' ')); I want the correct way to do it. The warning can be stopped by below code: auto temp = std::remove(stringVar.begin(), stringVar.end(), ' '); I dont want to use the return value of std:...
The problem here is that if you don't use temp you haven't properly removed the spaces from your string. The correct code is auto temp = std::remove(stringVar.begin(), stringVar.end(), ' ') stringVar.erase(temp, stringVar.end()); You see std::remove does not remove anything from anything (how can it when all it has ar...
64,763,717
64,763,821
Function that accepts a 2D array, multiplies it by an integer, and returns the new 2D array in C++?
say I have a 3x4 array with integer elements, I want to pass this array to a function that then takes all of the elements and multiplies them by some integer 'b' then returns this new array, how would I go about it? this is what I have currently #include <iostream> #include <math.h> using namespace std; // my functio...
Your function is not returning a new array, it's modifying an existing array. So (assuming this is not a problem for you) you should just change the return type to void. void multarray(int (*a)[4], int b) { ... } Then multarray(arr,3); for (int i = 0; i < 3; i++) { for (int j=0; j<4; j++) { cout <<...
64,764,313
64,764,347
How is operator+ implemented for strings?
can anyone show me more or less how is it implemented because if, for example i have string str1 = "hello"; string str2 = " world"; string str3 = str1 + str2; so because the code executes from right to left, this is getting executes, but how? str1 + str2 i mean what the returned value? because it needs to maybe alloca...
See this link: template< class CharT, class Traits, class Alloc > std::basic_string<CharT,Traits,Alloc> operator+( const std::basic_string<CharT,Traits,Alloc>& lhs, const std::basic_string<CharT,Traits,Alloc>& rhs ); You're basically calling the templated function which boils down to (gr...
64,764,581
64,766,427
Visual Studio Intellisense not working when inheriting from template class
Here is a testing snippet involving inheriting from template classes: #include <iostream> using namespace std; template <typename T> struct A { T x; }; template <typename T> struct B : public A<T> { B(T x, T y) : A<T>{ x }, y{ y } { } T y; }; template <typename T> struct C : public B<T> { C(T x, T y,...
I also get the same situation in my side. And I think it is a real issue of C++ Intellisense rather than C++ syntax standard. In fact, the project builds and runs well and can print the value of x without any errors, which proves that the issue is not related to C++ syntax standard. And it is just a pure C++ IntelliSen...
64,764,720
64,779,756
Dependecy between build server OS with generated binaries
I have a C++ and C# based code base (fairly large code base) which builds with Visual Studio. This application is Windows only and uses Win32/MFC/ASP.NET etc. Currently the build server we use to do the build is on Windows Server 2008 R2. Due to end of support of 2008 R2, I need to move the build server to a newer OS. ...
I think you worry too much about that. You do not have to care much about that. The generation of binary files, dependency on OS server are up to build tool and VS IDE itself, has nothing to do with the OS version. Especially the Build tool, the build tool parses your project to generate the corresponding binary file, ...
64,764,927
64,764,990
catch2 throws and error when adding a struct
This is the root of my project. I think I am missing a basic concept because the error occur when I wrap the the find() function in a struct. CMakeLists.txt bst.cpp bst.hpp bst-test.cpp catch.hpp CMakeLists.txt cmake_minimum_required(VERSION 3.16.4 FATAL_ERROR) project(bst LANGUAGES CXX) set(CMAKE_CXX_COMP...
you are declaring the Bst structure again in your .cpp file. The source file should only contain the definition of the methods, not the declaration of the structure. Changing bst.cpp to the following fixes the error: #include "bst.hpp" int Bst::find(int num, int array[]) { return -1; }
64,765,049
64,765,360
Simple Class and Header in Separate File Won't Work
I'm currently learning c++ for a week and here's my problem: run.cpp #include <iostream> #include "Abc.h" int main(){ int a; std::cout << "Enter a : "; std::cin >> a; // Object Initialization Abc AbcObj(); } the header, Abc.h : #ifndef ABC_H #define ABC_H class Abc { public: Abc();...
You error doesn't come up because you've used different files, so I have used one in this example struct Foo { int a; Foo() { std::cout << "Constructor called!"; } }; int main() { Foo obj(); } Why don't you see the message? You can read this thread The problem here is, Foo obj() is taken as...
64,766,212
64,766,363
Old GCC can not automatically find the new version libstdc++?
I'm trying to use the 3rd-party lib, called DocToText, with gcc 4.4.7. I compiled the program with: g++ -I./doctotext/ -L./doctotext/ -Wl,-rpath=./doctotext -ldoctotext -o example test_doctotext.cpp In the beginning, it returned libstdc++.so.6: version GLIBCXX_3.4.15 not found I manually downloaded the newer version, ...
Every GCC release is accompanied by its very own libstdc++ release. The C++ standard library (and support libraries like libsupc++) often rely on specific implementation details in the compiler, including bugs, and specific changes in behaviour due to defect reports etc. Sometimes even a new GCC release also needs a ma...
64,766,285
64,767,011
GTest - how to prepare data for multiple usage via SetUp method?
I am trying to run some google tests, and I have quite a lot of code to repeat in each test fixture, so I want to make the code as brief as possible, and I would like to use the SetUp method of the child class of Testing::test parent class, but the TEST_F fixtures do not recognize the variables from SetUp This is the s...
FooVar is a local variable inside the SetUp method. If you want to use it in the test fixtures, it needs to be a class member: class FooTest: public testing::Test { protected: int FooVar; virtual void SetUp() override { this.FooVar = 911; } }; In this example, if you are only set...
64,767,096
64,812,089
How to update clang without upgrading to Catalina
I've just got a MacOS 2 days ago with Mojave 10.14.5 and I was trying to install the latest Clang 12.0.0 but to no avail. I can't upgrade the OS to Catalina, so when I tried the XCode route I could only get the 13.1 version, with LLVM 10.0.1 and Clang-1001.0.46.4. Then I followed this guide : https://embeddedartistry.c...
homebrew installs binaries into /usr/local/bin, so you normally need to put that at the start of your PATH: export PATH=/usr/local/bin:$PATH You can check which clang will be run when you type clang in your Terminal by running: type clang If that tells you clang is /usr/bin/clang or /Applications/anything or /Library...
64,767,189
64,767,522
Which of these answers are the equivalent of O_RDWR on Ubuntu 14.04 LTS?
I have been given a list of the following check box containing all possible solutions to the question of choosing all true answers equivalent to O_RDWR on Ubuntu 14.04 LTS. according to this list below O_RDONLY 1 2 3 1 << 1 3 & 2 3 | 2 O_WRONLY (O_RDONLY + O_WRONLY) (O_RDONLY | O_WRONLY) (O_RDONLY & O_WRONLY) (O_RDONLY...
Look into bitwise operators. O_RDWR is defined in fcntl.h and is equals to 2. O_WRONLY = 1 O_RDONLY = 0 1 = 1 2 = 2 3 = 3 1 << 1 = 2 3 & 2 = 2 3 | 2 = 3 O_WRONLY = 1 (O_RDONLY + O_WRONLY) = 1 (O_RDONLY | O_WRONLY) = 1 (O_RDONLY & O_WRONLY) = 0 (O_RDONLY && O_WRONLY) = 0 (O_RDONLY << 1) = 1 (O_WRONLY << 1) = 2 0 = 0
64,767,734
64,768,155
Is double-construction undefined behaviour?
In our codebase, a pool of memory chunks is used and upon 'allocation' the object gets constructed using a "placement new". I'm missing the destructor call though, finding it odd to allow "double construction", and wonder if it is undefined behaviour to call the constructor another time on the same object. In C++11 3.8...
You can double construct without UB. The new object is a completely different one, and following pointers/references to the old one is UB. It is really easy to trip over UB when doing placement new, let alone when double constructing. Not calling a destructor just means the object is not cleaned up. If the destructor...
64,767,796
64,767,901
call of overloaded ‘abs(double&)’ is ambiguous
we have following code in legacy and use this place hundread of place. I am compiling code with c++11 and got following error. I can understand issue(saw couple of question on stackoverflow) as abs support int/long int in C++11. Is there any way to avoid 100 place and replace abs with fabs. Can I update such a way if ...
Why redefine what is already defined? You can find the function that you want in the header <cmath>. Further reading on c++ reference.
64,768,037
64,768,257
Using tcmalloc in a shared library
I have many executables that are linked with tcmalloc (.a). I usually do it at the executable level, so that any shared library loaded by the executable benefits from tcmalloc. However, I have a scenario where I need to provide a .so library to an user. Is it ok to use tcmalloc in that shared library? What happens if t...
Is it ok to use tcmalloc in that shared library? It depends on a few things: Whether your shared library is linked with tcmalloc in such a way that it exposes malloc and operator new as external symbols. Normally, it does. Whether the user of your library links to your library or loads it at run-time with dlopen and...
64,768,258
64,768,330
Object size of base class while referring to derived class
#include<bits/stdc++.h> using namespace std; class abc { public: int a = 45; void sum() { int s = 55; cout << s + a << endl; } }; class xyz: public abc { public: int b = 45; int c = 54; int d = 96; int x = 8; void show() { cout << "xyz class" << endl; } }; int main() { abc * ob; ...
The sizeof operator deals with static types, not dynamic ones. *ob is of static type abc, so that's the size it returns. Note that sizeof is performed at compile time, and there is no way that the compiler could figure out the dynamic type of an instance that is part of an inheritance hierarchy. In your snippet, it loo...
64,769,112
64,769,192
cpplinter in github actions
I want to install auto-checking my code with help of cpplint in Github actions. I try to install it in workflows file like that: - name: Install cpplint working-directory: ${{runner.workspace}}/uast shell: bash run: | pip install wheel pip install cpplint ...
Please try python -m cpplint: - name: cpplint working-directory: ${{runner.workspace}}/uast shell: bash run: python -m cpplint --recursive --exclude=source/catch.hpp --filter=-legal/copyright,-build/include_subdir source/* Modules installed over pip are not recognized as system level ...
64,769,154
64,769,297
Printing in binary format (user defined function)
I have implemented in C++ print_in_binary_format() function, which (as the name states) print 8-bit number in binary: void print_in_binary_format(std::uint8_t number) { for (int bit_index = 7; bit_index >= 0; --bit_index) { std::cout << ((number & (1U << bit_index)) ? '1' : '0'); } std::cout << '\n'...
The problem is your input data. You are providing 2 or 0 as a character, not as a number. Let me explain: character '2' -> ASCII 0x32, 32 is the real input of your function, 00110010 is the bit representation of 0x32. character '0' -> ASCII 0x30 has 00110000 as binary representation. Hence the function above is worki...
64,769,420
64,829,690
Antivirus detecting compiled C++ files as trojans
I had installed a c++ compiler for windows with MinGW. I tried to make a simple program: #include <iostream> using namespace std; int main() { cout << "Hello World!"; return 0; } And saved it as try.cc. Afterwards I opened cmd in the folder and ran g++ try.cc -o some.exe. It generated some.exe but my antivirus ...
Update: It actually was some kind of hash collision, the compiler wasn't infected. I did change the string in the print function, as suggested, several times, even adding line breaks, but everytime, my AV detected it as malware. I also tried deleting some lines of code (the includes and the print) and it also detected ...
64,769,422
64,770,877
How to automatically update a statusbar message?
I am using Qt 5.15.1 and C++ to create a simple app which processes signals from hardware and displays images and driver status. I want to update the statusbar message when an int value defined in another class changes. I would like this to happen automatically, each time this value changes. I understand that I need si...
The idea is that you want to emit your StatusChanged signal when the value has actually changed, not when you call GetStatus(). So you need a SetStatus() function, and your SignalProcessing class will need to know when to call that. Then you want to connect that signal to a slot that then updates your status bar. It mi...
64,769,506
64,769,682
Does Google's V8 require C++14 standard?
I am currently trying to build Google's V8 engine, following its official documents. And I get some errors here: Need a newer glibc python ../../tools/run.py ./bytecode_builtins_list_generator gen/builtins-generated/bytecodes-builtins-list.h ./bytecode_builtins_list_generator: /lib64/libstdc++.so.6: version `GLIBCXX_3...
Yes, V8 currently requires C++14. Expect future changes to be in the direction of requiring C++17 (though there's no timeline for that yet), rather than going back to older C++ standards.
64,769,886
64,777,616
How Can I Setup a FTP-Client Connection on embedded device?
I work on a FTP script for a mbed project. I work with the B-L475E-IOT01A development board and try to send a file to a FTP-Server. Therefore I cant establish a connection with the server with this libary https://os.mbed.com/users/dkato/code/ftp-client/#e069c405c934. Unfortunaly the client doesnt work like it should wo...
Julien, all the responses from the server follow a pattern.. you need to wait for a \r\n sequence from the server. You need to filter TELNET protocol escape sequences (that start with the byte 0xff or 0xfe, I don't remember from my head) and the codes must be always at the beginning of a line. Also the numbers with ...
64,770,045
64,770,147
Adding spaces between characters in string C++
I am looking for the most efficient way to add a space " " between every character in the string in C++. So let's say I pass a string "123" and I want to get "1 2 3 " or "1 2 3" (it doesn't really matter). Does anyone know the fastest way of doing such a thing? My method so far looks like this... string output; ...
You can write this conveniently with the range-v3 library. So given: namespace rs = ranges; namespace rv = ranges::views; std::string input = "123"; If you just want to print the string with interspersed spaces, you can do: rs::copy(input | rv::intersperse(' '), rs::ostream_iterator<char>(std::cout)); And ...
64,770,166
64,770,462
Why I can not use designated initalizers with structs that are not aggregates?
C++ has a nice new feature: struct Point{ int x; int y; int z; }; Point p{.x=47, .y=1701, .z=0}; But if I add a constructor then I am forbidden from using the nice designated initalizers syntax: struct Point{ Point(int x, int y, int z = 0): x(x), y(y), z(z){} int x; int y; int z; }; static Point p{.x=47, .y=1701, ...
Aggregate initialization (including initialization with designed initializers) circumvents the constructor of the class. This is not a problem for aggregates, since they aren't allowed to have user-defined constructors. But if you allow this kind of initialization for classes with user-provided constructors (that do so...
64,770,178
64,771,123
Can I set the child of an object to be an object defined separetely in PugiXML?
I want to configure a device using an XML file and was thinking that I can make the individual pugi::xml_nodes first with the values I need and later on make them children of a document or some parent node. However, I seem to be doing something wrong. Example that works: #include "pugixml.hpp" int main(){ pugi::xm...
pugixml documentation states that pugi::xml_node is a non-owning pointer to actual node data stored in a pugi::xml_document object: xml_node is the handle to document node; it can point to any node in the document, including the document node itself. There is a common interface for nodes of all types; the actual node ...
64,770,195
64,770,296
Saving a pointer to heap created in the local area
I made a "Planet" class and am trying to initialize a vector array based on this class in the client file of my project. bool addPlanet(std::vector<Planet>& planets, std::string filePath) { std::ifstream infile(filePath, std::ios_base::in); if (infile.fail()) { // File could not be opened retu...
Your code creates a Planet object: Planet* newPlanet = new Planet(sf::Vector2f(posX, posY), rotationZ, sf::Vector2f(scaleX, scaleY), planetMass, imagePath); Then, it copies this object into the vector: planets.push_back(*newPlanet); But it doesn't release the memory corresponding to the original object. The vector on...
64,770,338
64,778,472
Purpose of class ExplicitInit in objc runtime source code
I'm studying class ExplicitInit in objc runtime source code. I know that class ExplicitInit is used in static objc::ExplicitInit<StripedMap<SideTable>> SideTablesMap;. But why ExplicitInit is necessary? StripedMap is good enough to store SideTable. I think the comments for class ExplicitInit in DenseMapExtras.h is the ...
We cannot use a C++ static initializer to initialize certain globals because libc calls us before our C++ initializers run. There is some deep dyld and Mach-O voodoo that I don't understand when it comes to the Objective-C runtime! This was a fun question to try dig into. The function _objc_init() (in objc-os.mm) per...
64,770,392
64,776,679
cmake issue with FetchContent same protobuf dependency between grpc and or-tools
im using the FetchContent from cmake to manage my dependencies FetchContent_Declare( protobuf GIT_REPOSITORY https://github.com/protocolbuffers/protobuf.git GIT_TAG v3.13.0 SOURCE_SUBDIR cmake ) ## END PROTOBUF ## ## GRPC ## FetchContent_Declare( grpc GIT_REPOSIT...
cross posting... already answered here: https://github.com/google/or-tools/issues/2219 modify deps.cmake (or cpp.cmake on stable v8.0) to if(NOT BUILD_Protobuf AND NOT TARGET protobuf::libprotobuf) find_package(Protobuf REQUIRED) endif() related to: https://gitlab.kitware.com/cmake/cmake/-/issues/17735
64,770,824
64,771,388
Mapping a continuous range into discrete bins in C++
I've inherited maintenance of a function that takes as parameter a value between 0 and 65535 (inclusive): MyClass::mappingFunction(unsigned short headingIndex); headingIndex can be converted to degrees using the following formula: degrees = headingIndex * 360 / 65536 The role of this function is to translate the headin...
The shown code looks very convoluted (it is possibly a guard against integer overflow). A far simpler way to determine the symbol number would be code like the following: symbol = (headingIndex * 36u) / 65536u; However, if this does present problems with integer overflow, then the calculation could be done in doub...
64,771,581
64,774,286
Format a constexpr const char*
I'm working with __ PRETTY_FUNCTION __, C++11, that is formated like: (type Class::Object(parameters), but I need to format my string like (Class::Object()). I know how to remove "type" from my string with constexpr. I can simply return a pointer skipping space, like this: inline constexpr const char* removeType(const ...
I took a crack, ignoring the obvious caveat that __PRETTY_FUNCTION__ is a propriety GNU convention that can't be counted on for any guarantees in the formatting. My strategy was to start at the last ')', and then do a search for '(' while balancing parenthesis to avoid tricky parameters like function pointers. But then...