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
69,178,927
69,179,020
CAN Communication in QT
I have a specific problem with the CAN communication in QT. It is not a problem to send/write CAN messages, but the readFrame() function in QT doesn't load my received frames. If you are implementing a CAN communication in C++ you can use the read() and write() functions. But in QT it is not supported. In general the read function interrupts the programm until a message is received, how can I do the same in QT? QCanBusFrame frame = device->readFrame(); Thanks for your help, I really appreciate it!
From the QT docs: Returns the next QCanBusFrame from the queue; otherwise returns an empty QCanBusFrame. The returned frame is removed from the queue. The queue operates according to the FIFO principle. https://doc.qt.io/qt-5.12/qcanbusdevice.html#readFrame Try first calling bool QCanBusDevice::waitForFramesReceived(int msecs) https://doc.qt.io/qt-5.12/qcanbusdevice.html#waitForFramesReceived and then read frames
69,179,378
69,179,506
Why use a dynamic array instead of a regular array?
The following code is used to demonstrate how to insert a new value in a dynamic array: #include <iostream> int main() { int* items = new int[5] {1, 2, 3, 4, 5}; // I have 5 items for (int i = 0; i < 5; i++) std::cout << items[i] << std::endl; // oh, I found a new item. I'm going to add it to my collection. // I do this by // (1) allocating a bigger dynamic array // (2) copying the existing elements from the old array to the new array // (3) deleting the old array, redirecting its pointer to the new array int* items_temp = new int[6]; for (int i = 0; i < 5; i++) items_temp[i] = items[i]; items_temp[5] = 42; delete[] items; items = items_temp; for (int i = 0; i < 6; i++) std::cout << items[i] << std::endl; delete[] items; } I am confused about the necessity of using it over a regular array. Can't I just do the same thing with a regular array? Basically, you just define a new array with a larger size and move elements in the previous array to this new array. Why is it better to use a dynamic array here?
You are right, the example you are looking at isn't very good at demonstrating the need for dynamic arrays, but what if instead of going from size 5->6, we had no idea how many items we found until we need to add until the code is actually running? Regular arrays need to be constructed with their size known at compile time int foo [5] = { 16, 2, 77, 40, 12071 }; But dynamic arrays can be be assigned as size at runtime int* Arrary(int size) { return new int[size]; } So if you don't know the size of your array, or it may need to grow/shrink you need to use a dynamic array (or better yet just use a std::vector).
69,179,467
69,179,855
What does "semantics" mean? and why are "move semantics" named as such, instead of any other term?
In Cpp, the "move semantics" of an object refers to the concept that "move but not copy the object to a newer", but the word "semantics" really confuse me. What is the difference between the "semantics" and "function"? How to use this word correctly? If I realize a method called "max(A,B)", could we say "I realize a max semantic"? If I coding a object called "list", could we say "I realize a sequence storage semantic"?
"Semantics" is the meaning or interpretation of written instructions. It is often contrasted to "syntax", which describes the form of the instructions. For example, an assignment foo = bar has the same form in many programming languages, but not necessarily the same meaning. In C++ it means copy, in Rust it means move, and in Java or Python it means copy the object reference. "Move semantics" applied to C++ syntax such as assignment or passing parameters to functions means that that syntax is or can be interpreted as object move as opposed to object copy. Semantics is not a synonym for "function", so "max semantics" doesn't make much sense. Other examples where the word can be applied is reference semantics as opposed to value semantics, or "short-circuit semantics" (of the && and || operators) as opposed to evaluating all clauses. Basically, anything where there are multiple possible meanings of what you wrote, and you need to name and pinpoint the correct one.
69,180,773
69,183,872
Specify callback function in enet
The ENet library has packets that can be send, and includes a callback function once it has finished sending that specific packet. http://enet.bespin.org/structENetPacket.html#ad602d6b6b35ef88b2b2e080fa5c9dc3d typedef struct _ENetPacket { size_t referenceCount; /**< internal use only */ enet_uint32 flags; /**< bitwise-or of ENetPacketFlag constants */ enet_uint8 * data; /**< allocated data for packet */ size_t dataLength; /**< length of data */ ENetPacketFreeCallback freeCallback; /**< function to be called when the packet is no longer in use */ void * userData; /**< application private data, may be freely modified */ } ENetPacket; The callback itself: typedef void (ENET_CALLBACK * ENetPacketFreeCallback) (struct _ENetPacket *); Now I want to create a class that holds the host used to send those packets, and also to keep track how many packets were successfully sent. template<typename T> class Sender { public: explicit Sender() { } void send(T* data, int32_t length) { ENetPacket* packet = enet_packet_create(data, length, ENET_PACKET_FLAG_RELIABLE); packet->freeCallback = callbackPacket; enet_host_broadcast(m_server, 0, packet); } void callbackPacket(ENetPacket* packet) { --m_counter_packets_active; } }; This does not compile: Error C3867 Sender<int32_t>::callbackPacket': non-standard syntax; use '&' to create a pointer to member When I try packet->freeCallback = &this->callbackPacket; I get Error C2440 '=': cannot convert from 'void (Sender<int32_t>::* )(ENetPacket *)' to 'ENetPacketFreeCallback' I just don't understand what the proper code would be for the packet calling the Sender object's method when the packet is done with.
Okay, this is pretty common. First, you can't call a non-static member method this way, not directly. Pain in the ass. But that callback structure has a userData field. And that's what we're going to use. void send(T* data, int32_t length) { ENetPacket* packet = enet_packet_create(data, length, ENET_PACKET_FLAG_RELIABLE); packet->freeCallback = &Sender::myStaticMethod; packet->userData = this; // This is part of the magic enet_host_broadcast(m_server, 0, packet); } static void myStaticMethod(ENetPacket * packet) { Sender * sender = static_cast<Sender *>(packet->userData); sender-> callbackPacket(packet); } In other words -- store this as your user data. Use a static method for the callback, and have him turn it around to call your real callback.
69,181,509
69,183,937
Calculating Accumulated Value with C++
I'm asked to write a program that reads in an investment amount, annual interest rate, and a number of years, and displays the future investment value using the following formula. futureInvestmentValue = investmentAmount x (1 + monthlyInterestRate)(numberOfYears X 12) assuming that monthlyInterestRate = annualInterestRate / 12.0. However, I am not supposed to include any math libraries (which would have made things a whole lot easier, such as the pow() function). My main issue is with the accumulatedValue property, where (1.0 + monthlyInterestRate) * (numberOfYears * 12.0) should be an exponent rather than just multiplication. I'm struggling to figure out how exactly that would work. // This is my code here #include <iostream> using namespace std; int main() { double futureInvestmentValue; double investmentAmount; double annualInterestRate; double monthlyInterestRate = annualInterestRate / 12.0; double numberOfYears; cout << "Enter investment amount: "; cin >> investmentAmount; cout << endl; cout << "Enter annual interest rate in percentage: "; cin >> annualInterestRate; cout << endl; cout << "Enter number of years: "; cin >> numberOfYears; cout << endl; double accumulatedValue = investmentAmount * (1.0 + monthlyInterestRate) * (numberOfYears * 12.0); cout << "Accumulated value is " << accumulatedValue <<endl; return 0; }
Let me answer for various use-cases of your question. Answer with a whole number of years You actually do not need the monthly interest rate at all, as accumulatedValue = investmentAmount × (1.0 + 0.01*annualInterestRate)numberOfYears Here, annualInterestRate is multiplied by 0.01, as you asked the user for a percentage. With the assumption of whole years, the calculation can be performed as follows: double accumulatedValue = investmentAmount * getGrowthFactorFor(numberOfYears, annualInterestRate); with double getGrowthFactorFor( int periods, double periodInterestPercentage) { double yearlyGrowth = 1.0 + 0.01 * periodInterestPercentage; double accumulatedGrowth = 1.0; for (int i = 0; i < periods; i++) { accumulatedGrowth *= yearlyGrowth; } return accumulatedGrowth; } This is an exact answer, for as far as floating-point calculus is exact. Using a double will likely not represent any problems before the United Federation of Planets is long gone… This calculation is not very fast for a large amount of years, and you could replace getGrowthFactorFor with a faster algorithm, like exponentiation by squaring as suggested in @chux - Reinstate Monica's answer. If you do not need an exact answer, and you have a rather small combination of years and the interest percentage, you can also approximate the accumulated value in a single statement with double accumulatedValue = investmentAmount * (1.0 + 0.01 * annualInterestRate * numberOfYears); This uses the power approximation described below. Answer with a fractional number of years. To do this, you can start with calculating the growth-factor for the whole number of years. Then you use the power approximation (below) to calculate the growth factor for the fractional remainder. int wholeYears = numberOfYears; double yearFraction = numberOfYears - wholeYears; double growthFactorWholeYears = getGrowthFactorFor(numberOfYears, annualInterestRate) double growthFactorFractionalYears = getGrowthFactorFor(1, annualInterestRate * yearFraction); // Tada! accumulatedValue = investmentAmount * growthFactorWholeYears * growthFactorFractionalYears; This is not an exact solution, but for, say 10% interest and half a year, you have the difference between a correctly calculated growth of 1,0488 and an approximated growth of 1.05. That's not even a percent off! And as the whole year calculation is exact, the final result is never far off from the actual value. Power approximation If ε > 0 x > 0 x × ε much smaller than 1 α is plus or minus ε then (1 + α)x approximates ~ (1 + αx) This is the first order Taylor approximation, but I won't bother you with that.
69,182,016
69,182,295
Returning std::unique_ptr to abstract type with custom deleter from a memory pool
Assume I have a templated MemoryPool class a function create(...) (which returns a pointer to a newly allocated object of type T) and a function destroy(T*) (which destroys and returns the memory back to the pool). I would like to create a std::unique_ptr that "owns" the pointer created by the pool and returns the pointer to the pool, thus requiring a custom deleter. The problem is, how do I make this work if the pool contains concrete objects and I want to pass around a std::unique_ptr to an abstract interface of this object. Here is an example that doesn't compile: #include <iostream> #include <memory> #include <functional> #include <utility> template <typename T> class MemoryPool { public: template <typename ... ARGS> T* create(ARGS&&... args) { std::cout << "MemoryPool::create()" << std::endl; return new T(std::forward<ARGS>(args)...); } void destroy(T* ptr) { std::cout << "MemoryPool::destroy()" << std::endl; delete ptr; } }; class ITest { public: ITest() { std::cout << "ITest::ITest()" << std::endl; } virtual ~ITest() { std::cout << "ITest::~ITest()" << std::endl; } virtual void sayHello() = 0; }; class Test :public ITest { public: Test() { std::cout << "Test::Test()" << std::endl; } ~Test() { std::cout << "Test::~Test()" << std::endl; } void sayHello() override { std::cout << "Test says hello" << std::endl; } }; class ITestOwner { public: ITestOwner(std::unique_ptr<ITest> ptr) : _ptr(std::move(ptr)) { std::cout << "ITestOwner::ITestOwner()" << std::endl; } ~ITestOwner() { std::cout << "ITestOwner::~ITestOwner()" << std::endl; } void sayHello() { _ptr->sayHello(); } private: std::unique_ptr<ITest> _ptr; }; int main() { MemoryPool<Test> pool; std::unique_ptr<Test, std::function<void(Test*)>> ptr(pool.create(), [&pool](Test* ptr){ std::cout << "Custom Deleter" << std::endl; pool.destroy(ptr); }); ITestOwner owner(std::move(ptr)); owner.sayHello(); return 0; } Keep in mind that, my real MemoryPool class would actually act as a normal memory pool and not use new/delete as I have done. In this example, ITestOwner should take over ownership of the std::unique_ptr to a ITest abstract object. Then, when ITestOwner is destroyed, the smart pointer will be destroyed, and the Test object should be returned to the memory pool. Is there a way to accomplish this?
The code doesn't compile because std::unique_ptr<ITest> is used by ITestOwner while you to forward it std::unique_ptr<Test, std::function<void(Test*)>>. It obviously doesn't compile because std::unique_ptr<ITest> calls delete on ITest instead of calling some complex arbitrary function. You'd need to use unique_ptr<ITest, function<void(ITest*)>> for it to work and in addition add some unsighty conversion code from function<void(Test*)> to function<void(ITest*)>... I'd say this is simply not good. unique_ptr is designed to be simple and efficient - the destructor is supposed to wrap basic functionality but it isn't convenient enough for complicated purposes. Basically, unique_ptr is not designed for this task. It is supposed to be lightweight and you already use heavy functionality like std::function that ruins the whole purpose. Instead, you can use shared_ptr which type erases the deleter and hides it - so you'd need nothing to worry about. If you want to still restrict user to unique ownership you can surely find other 3rd party open source libraries that implement the smart pointer you want - there are lots of them.
69,182,146
69,184,849
Multi-track audio playback C++ / PortAudio
I am working on a synthesizer/live-coding application where I want to have multiple instances of the engine generate different sounds with different sequences. (aside: I have the synth engine working with MIDI input). Let's say the user input to the console may look something like this: track:1,sound:pad,seq:[70, sleep 0.25, 77, sleep 0.5] track:2,sound:bass,seq:[30, sleep 0.125, 30, sleep 0.125, 31, sleep 0.5] play How can I interleave the timing of these two sets of events with the correct sleeps? I feel like there has got to be some way to synchronize these two series of events, I don't know if the answer is multithreading or some other syncing mechanism. What area of programming should I be looking at? Apologies if this question is unclear or totally naive. for example, I'm nearly certain the following would not do what I think it does: # after issuing play command, the following events are generated, which clearly does not interleave these timing events while (true) { stream.noteOn(70, track1); bpmSleep(0.25, track1); // beats stream.noteOff(70, track1); stream.noteOn(77, track1); bpmSleep(0.5, track1); stream.noteOff(77, track1); stream.noteOn(30, track2); bpmSleep(0.125, track2); stream.noteOff(30, track2); // etc. }
Convert your input data to the same representation as MIDI: event type, track, parameters, time. Then sort the two tracks together by time, and process all the events: grab next event, sleep until the time that event is supposed to happen, repeat. This is really what MIDI is. A scheduled event representation. In MIDI, NOTE ON is a completely separate event from NOTE OFF, so an event doesn't even have a duration. If you imagine each track as a sequence of discrete events, all you need to do is be sure each event has the data to know which track it belongs in, and you can process them all in one queue. Note that sleep doesn't need a track. It's the absence of events, not an event itself. Also note that you don't even need two channels for this. Its common to play multiple voices on the same channel. // pseudocode struct event { enum {NOTE_ON, NOTE_OFF} event_type; int note; }; while(true) { ev = events.pop(); bpmSleep(ev->time - now); if(ev->event_type == NOTE_ON) stream.noteOn(ev->note, ev->channel); else if(next_event->event_type == NOTE_OFF) stream.noteOff(ev->note, ev->channel); }
69,182,612
69,183,765
Storing a vector of vectors of type int in a Redis cache
I'm using the redis-plus-plus C++ redis client to store data in a redis cache and I would like to know how to store an std::vector<std::vector<int>> object. From the provided examples in the git repository there isn't a similar example. If there is another C++ client that can simplify the storage and retrieval of such a data structure may you also suggest.
There are a few ways. You could serialize this and store a big string. You could use lists. For the double-nesting thing, you'd have to get clever with the keys. What I would do would depend on how I have to access it. But you'll have to code it yourself, somehow.
69,183,044
69,183,099
issue in intialising character array from the structure through an array object
i am getting an issue while initialising the character array in the structure through the structure object #include <iostream> #include <string.h> using namespace std; struct emp { int age; char name[10]; }; int main() { struct emp v[2]; List item v[0].age = 9; v[0].name[] = "name1"; <-this is where i am getting error v[1].age = 10; v[1].name[]= "name2"; <-this is where i am getting error for (int i = 0; i < 2; i++) { cout << v[i].age << " " << v[i].name<<endl; } return 0; }
For starters there is at least a typo v[0].name[] = "name1"; <-this is where i am getting error ^^^^ v[1].name[]= "name2"; <-this is where i am getting error ^^^^ Arrays do not have the assignment operator. So these assignment statements v[0].name[] = "name1"; v[1].name[]= "name2"; are incorrect syntactically and semantically. You could initialize the elements of the array when it is declared. For example struct emp v[2] = { { 9, "name1" }, { 10, "name2" } }; Otherwise you could use the standard string function strcpy. For example #include <cstring> //... v[0].age = 9; strcpy( v[0].name, "name1" ); v[1].age = 10; strcpy( v[1].name, "name2" ); Another approach is to use class std::string instead of the character array. For example #include <string> // ... struct emp { int age; std::string name; }; int main() { struct emp v[2]; v[0].age = 9; v[0].name = "name1"; v[1].age = 10; v[1].name= "name2"; for (int i = 0; i < 2; i++) { cout << v[i].age << " " << v[i].name<<endl; } return 0; } Pay attention to that instead of the ordinary for loop you could use the range-based for loop. For example for ( const auto &item : v ) { cout << item.age << " " << item.name << endl; }
69,183,440
69,183,841
Anonymous implementation of interface in C++
Does C++ support anonymous implementation of interface like Java? Something similar like in following code: Runnable myRunnable = new Runnable(){ public void run(){ System.out.println("Runnable running"); } }
You can get pretty close by creating an instance of an anonymous class that inherits from your defined interface. Example: #include <iostream> struct Runnable { virtual ~Runnable() = default; virtual void operator()() = 0; }; int main() { struct : Runnable { // anonymous implementation of interface void operator()() override { std::cout << "Run Forrest\n"; } } myRunnable; myRunnable(); // prints Run Forrest } Here's a contrived example, putting base class pointers to instances of different anonymous implementations of Runnable in a std::vector<std::unique_ptr<Runnable>>. As you can see here, making the implementations anonymous serves little purpose. The anonymous type is simply std::remove_reference_t<decltype(*instance)>. #include <iostream> #include <memory> #include <type_traits> #include <vector> // Runnable is defined as in the example above int main() { // a collection of Runnables: std::vector<std::unique_ptr<Runnable>> runners; { // create a pointer to an instance of one anonymous impl. struct : Runnable { void operator()() override { std::cout << "Foo\n"; } } *instance = new std::remove_reference_t<decltype(*instance)>; runners.emplace_back(instance); // save for later } { // create a pointer to an instance of another anonymous impl. struct : Runnable { void operator()() override { std::cout << "Bar\n"; } } *instance = new std::remove_reference_t<decltype(*instance)>; runners.emplace_back(instance); // save for later } // loop through all `Runnable`s and ... run them: for(auto& runner : runners) (*runner)(); // prints "Foo\nBar\n" }
69,183,632
69,183,703
How can you partially fill an array in C++
I'm working on trying to partially fill an array, however when running, the program continues to run past the limit that was given by the user. Is there another way to partially fill an array? The initial NUM_ROWS and NUM_COLUMNS constants are placeholders until the program work #include <iostream> // Input and output #include <iomanip> // Input manipulator #include <array> using namespace std; // Number used to initialize an array const int NUM_ROWS = 10; const int NUM_COLS = 10; int userFilledArray[NUM_ROWS][NUM_COLS]; int row; // Amount of rows the user will fill int col; // Amount of columns the user will fill int main() { int num; // Number that is placed in a specific row and column int total; // Total of every integer in the array int average; // Average of every integer in the array int rowTotal; // Total of every integer in a specific row int colTotal; // Total of every integer in a specific column int highestInRow; int lowestInRow; // Asks the user to enter the number of rows they would like to fill cout << "How many rows in the array would you like to fill? (Between 1 - 10)" << endl; cin >> row; // Asks the user to enter a number between 1-10 if the user enters a character or integers not between 1-10 while (row < 0 || row > 10) { cout << "Please enter a number between 1-10" << endl; cin >> row; } // Asks the user to enter the number of columns they would like to fill cout << "How many columns in the array would you like to fill? (Between 1 - 10)" << endl; cin >> col; // Asks the user to enter a number between 1-10 if the user enters a character or integers not between 0-10 while (col < 0 || col > 10) { cout << "Please enter a number between 1-10" << endl; cin >> col; } // Now the user will fill the array with as many numbers needed for (int i = 0; i < row; i++) // WARNING!!! NOT WORKING { for (int j = 0; i < col; j++) // WARNING!!! NOT WORKING { cout << "Enter a number for row " << i << " and column " << j << endl; cin >> num; userFilledArray[i][j] = num; } } total = getTotal(userFilledArray); cout << total << endl; } This is the area that is not working properly // Now the user will fill the array with as many numbers needed for (int i = 0; i < row; i++) // WARNING!!! NOT WORKING { for (int j = 0; i < col; j++) // WARNING!!! NOT WORKING { cout << "Enter a number for row " << i << " and column " << j << endl; cin >> num; userFilledArray[i][j] = num; } } }
This is your problematic line: for (int j = 0; i < col; j++) // WARNING!!! NOT WORKING And it also demonstrates why single-letter variable names lead to bugs. You cut and pasted this from the previous for-loop, and you didn't change every instance of variable i.
69,184,012
69,184,093
Overload std::unique_ptr deleter method using std::enable_if
I am trying to write a deleter for my std::unique_ptr, and I would like to overload the method for deletion. Here is what I tried, but the compiler complains about the use of std::enable_if_t. Code is compiled using -std=c++20 flag. template <class T> class custom_deleter { public: template <class U, std::enable_if_t<std::is_array_v<T>, bool> = true> void operator()(U* ptr) { std::cout << "array"; } template <class U, std::enable_if_t<!std::is_array_v<T>, bool> = true> void operator()(U* ptr) { std::cout << "non-array"; } }; Here's the compiler error: main.cpp:17:10: error: no type named 'type' in 'struct std::enable_if<false, bool>' 17 | void operator()(U* ptr) { std::cout << "non-array"; } | ^~~~~~~~ I don't understand the issue. At first, I thought I was missing an included or compile flag for std::enable_if_t to be available, but its not the problem here. Any help appreciated.
SFINAE required a template parameter of the function to be depended on. That means the std::enable_if_t can only be applied for the U not for the class template T. Therefore, you need to include the template parameter T in your operator()s somehow (like class U = T) or just if constexpr the operator() as you are anyway have acces to c++20: template <class T> class custom_deleter { public: template <class U = T> void operator()(U* ptr) { if constexpr(std::is_array_v<U>) std::cout << "array"; else if constexpr(!std::is_array_v<U>) std::cout << "non-array"; } }; int main() { custom_deleter<int[2]> arrDel; custom_deleter<std::string> strDel; return 0; }
69,184,482
69,184,533
C++ How to Save Elements in a Vector from a Function
Consider the following code. In list1 I'm adding elements saved on the heap to a vector and printing. It works as expected. In list2 I'm adding elements onto the vector from a function which also allocates elements on the heap. I understand I have to allocate Node on the heap in addNode as otherwise it would be deallocated when the function returns. However, via the final print statement I can see the nodes on the heap are still allocated, yet they don't show up in my vector. #include <iostream> #include <vector> using namespace std; /* Simple node class for demo */ class Node { public: string val; Node(string value) { this->val = value; } }; Node *addNode(vector<Node *> list) { // allocate space for node on the heap so it isn't destroyed after function returns auto node = new Node("foo"); // add pointer to node onto vector list.push_back(node); return node; } /* Simple function for printing vector contents */ template <typename T> void printVector(T d) { cout << "Vector has size " << d.size() << " and elements: "; for (auto p = d.begin(); p < d.end(); p++) { cout << (*p)->val << ","; } cout << "\n"; } int main() { // make a new vector vector<Node *> list1; // add elements allocated on the heap list1.push_back(new Node("foo")); list1.push_back(new Node("foo")); list1.push_back(new Node("foo")); printVector(list1); // prints: "Vector has size 3 and elements: foo,foo,foo," // make a new vector vector<Node *> list2; // add elements allocated on the heap from a function addNode(list2); addNode(list2); // save one of the nodes to a variable for demonstration auto node = addNode(list2); printVector(list2); // prints: "Vector has size 0 and elements:" cout << node->val << "\n"; // prints: "foo" return 0; } Can someone explain how to add elements to a vector from a function?
In addNode(), you are passing the vector by value, thus a copy of the caller's vector is made, and then you are adding the Node* to the copy, the original vector is unaffected. You need to pass the vector by reference instead: Node* addNode(vector<Node*> &list) Same with printVector(). You are passing the vector by value, you are just not modifying the copy, but you should still pass the vector by (const) reference to avoid making a copy at all: template <typename T> void printVector(const T &d) On a side note, you are leaking the Nodes you create. You need to delete them when you are done using them: int main() { vector<Node*> list1; list1.push_back(new Node("foo")); list1.push_back(new Node("foo")); list1.push_back(new Node("foo")); printVector(list1); for(auto *p : list1) delete p; vector<Node*> list2; addNode(list2); addNode(list2); auto node = addNode(list2); printVector(list2); cout << node->val << "\n"; for(auto *p : list2) delete p; return 0; } Better to use std::unique_ptr to manage that for you: #include <iostream> #include <vector> #include <memory> using namespace std; ... Node* addNode(vector<unique_ptr<Node>> &list) { list.push_back(make_unique<Node>("foo")); return list.back().get(); } template <typename T> void printVector(const T &d) { cout << "Vector has size " << d.size() << " and elements: "; for (const auto &p : d) { cout << p->val << ","; } cout << "\n"; } int main() { vector<unique_ptr<Node>> list1; list1.push_back(make_unique<Node>("foo")); list1.push_back(make_unique<Node>("foo")); list1.push_back(make_unique<Node>("foo")); printVector(list1); vector<unique_ptr<Node>> list2; addNode(list2); addNode(list2); auto node = addNode(list2); printVector(list2); cout << node->val << "\n"; return 0; }
69,184,772
69,184,949
_alloca and std::vector of const char*
I did several searches on the _alloca function and it is generally not recommended. I will have a dynamically updated array of strings on which I will have to iterate often. I would like to have each string allocated on the stack to reduce the miss caches as much as possible. Using _alloca I could create a char* on the stack and put it in the vector. My char will be in a vector which will not impact my stack and I know that the strings will never be big enough to make a stackoverflow when I allocate them on the stack. Is it a bad thing to use it in this case? Does the program do what I want it to do? #include <vector> #include <cstring> #ifdef __GNUC__ # define _alloca(size) __builtin_alloca (size) #endif /* GCC. */ std::vector<const char*> vec; void add(const char* message, int size) { char* c = (char*) _alloca (size * sizeof(char*)); std::memcpy(c, message, sizeof(message)); vec.push_back(c); } int main() { const char* c = "OK"; for (int i = 0; i < 10; ++i) { add(c, 2); } }
Stack memory allocated by _alloca gets automatically released when the function that calls _alloca returns. The fact that a pointer to it gets shoved someplace (specifically some vector) does not prevent this memory from being released (as you mentioned you assumed would happen, in the comments), that's not how C++ works. There is no "garbage collection" in C++. Therefore, the shown code ends up storing a pointer to released stack memory. Once add() returns, this leaves a dangling pointer behind, and any subsequent use of it results in undefined behavior. In other words: yes, it's "a bad thing to use it in this case", because be the shown code will not work. There are also several other, major, issues with this specific _alloca call, but that's going to be besides the point. This entire approach fails, even if these issues get fixed correctly.
69,184,830
69,184,996
Is a requires expression an atom when normalizing constraints?
I want to make sure I properly understand the constraint normalization process since cppreference is slightly fuzzy on this topic. It seems that during the normalization, anything that is inside of a requires expression is always considered an atom, no matter how specific/complex. This seems to be supported by the different handling of: template<typename T> concept Decrementable = requires(T t) { --t; }; template<typename T> concept RevIterator = Decrementable<T> && requires(T t) { *t; }; template<typename T> concept RevIterator2 = requires(T t) { --t; *t; }; Where Decrementable < RevIterator but Decrementable and RevIterator2 are not ordered. So, is this correct? Or can someone point me to the specific part of the standard that talks about this?
Yes your understanding is correct. For subsumption (what you denote by <) to occur, there has to be a certain relationship between the normal forms of the constraint expression. And if one examines the constraint normalization process: [temp.constr.normal] 1 The normal form of an expression E is a constraint that is defined as follows: The normal form of an expression ( E ) is the normal form of E. The normal form of an expression E1 || E2 is the disjunction of the normal forms of E1 and E2. The normal form of an expression E1 && E2 is the conjunction of the normal forms of E1 and E2. The normal form of a concept-id C<A1, A2, ..., An> is the normal form of the constraint-expression of C, after substituting A1, A2, ..., An for C's respective template parameters in the parameter mappings in each atomic constraint. If any such substitution results in an invalid type or expression, the program is ill-formed; no diagnostic is required. [ ... ] The normal form of any other expression E is the atomic constraint whose expression is E and whose parameter mapping is the identity mapping. one sees that logical AND expressions, logical OR expressions, and concept-ids are the only expressions that get "broken down". Every other sort of expression pretty much forms its own atomic constraint, including a requires expression like requires(T t) { --t; *t; }.
69,184,977
69,185,176
"invalid operands to binary expression" in simple class using memory and addresses
#include <iostream> using namespace std; class Animal { public: string eat() { return "I can Eat"; } string sleep() { return "I can sleep"; } void showData(int *weight, int *age) { cout << "The weight is " << weight << " and the age is " << age << endl; } }; int main() { Animal an; int x; int y; cout << "Enter the height and weight of the dog." <<endl; cin >> x; cin >> y; cout << an.eat()<< endl; cout << an.sleep()<<endl; cout << an.showData(&x,&y) << endl; return 0; } At the part that states: cout << an.showData(&x,&y) I get an error stating: invalid operands to binary expression I thought that by using addresses, I can instantly be able to output the function, but apparently I guess there is some incompatibility?
showData() returns void, ie nothing. So there is nothing to pass to operator<<, hence the error. Simply change cout << an.showData(...) to an.showData(...), since showData() does its own cout statements internally. If you want cout << an.showData(...) to actually display something, then showData() needs to return something worth displaying, such as a std::string, eg: string showData(int *weight, int *age) { return "The weight is " + to_string(*weight) + " and the age is " + to_string(*age); } Animal an; cout << an.showData(&x,&y) << endl;
69,185,315
69,198,495
How to install c++ program into conda environment from source
I would like to compile and then use the scientific project BASS, which is distributed as c++ source code on github. I've set up a conda environment bass to hold everything related to BASS, and I'd like to compile BASS into this environment (so that if I delete the environment, it's cleanly removed). I don't know if I should be using conda-build or make to do this. There is a Makefile distributed with the project, but I think it might have an error. My latest try is the following: (the source files are in code/ and gsl seems to be a dependency): conda create -n bass conda activate bass conda install make conda install gsl cd code/ make I get the following: gcc -c main.cpp -I../Libs/GSL/include/ -I./ main.cpp:19:10: fatal error: 'gsl/gsl_statistics.h' file not found #include <gsl/gsl_statistics.h> ^~~~~~~~~~~~~~~~~~~~~~ 1 error generated. make: *** [Makefile:11: main.o] Error 1 My questions: should I be doing this with make? do I need gcc/g++/cxx-compiler installed in my conda env? is the Makefile correct where it says "-I../Libs/GSL/include/" Thank you!
Here's a very basic Conda recipe for the package. Make a folder (say recipe) and put the following two files in it: meta.yaml package: name: bass version: 0.1 # this is totally arbitrary (there are no versions) source: git_url: https://github.com/judyboon/BASS.git requirements: build: - {{ compiler('cxx') }} host: - gsl run: - gsl about: home: https://github.com/judyboon/BASS license: GPL-3.0-only license_file: COPYING license_family: GPL build.sh #!/bin/bash ## change to source dir cd ${SRC_DIR}/code ## compile ${CXX} -c main.cpp *.cpp -I./ ${CXXFLAGS} ## link ${CXX} *.o -o BASS -lgsl -lgslcblas -lm ${LDFLAGS} ## install mkdir -p $PREFIX/bin cp BASS ${PREFIX}/bin/BASS You can then build this with conda build ., run from in that directory. Installing After successful build, you can create an environment with this package installed using conda create -n foo --use-local bass Since I'm on an Intel architecture, and this tool uses CBLAS, I would further specify to use MKL: conda create -n foo --use-local bass blas=*=*mkl Now if you activate the environment foo (that's an arbitrary name), the software will be on PATH, under the binary BASS. Additional Notes I verified this works on osx-64 platform with the conda-forge channel prioritized. The Makefile accompanying the code isn't very generic. Here we just have it compile all .cpp files and subsequently link all .o files. There aren't any releases on the repository, so the versioning in the meta.yaml is arbitrary. The build.sh defines the final output binary as BASS - that could be changed, and differs from the original Makefile which outputs the binary as main.
69,185,463
69,199,226
How do I get cppyy to find additional headers?
I have a directory structure: include/foo/bar/header1.h include/foo/bar/header2.h header1.h includes header2.h. However, when I attempt this: import cppyy cppyy.add_include_path('include') cppyy.include('foo/bar/header1.h') I get the error: ImportError: Failed to load header file "foo/bar/header1.h" In file included from input_line_33:1: ./include/foo/bar/header1.h:11:10: fatal error: 'foo/bar/header2.h' file not found #include "foo/bar/header2.h" ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ I am not sure what to do here. I could include header2.h manually, but it in turn has other include files and I would probably end up including the entire project manually, which seems like it doesn't need to happen. I have tried both cppyy.include('include/foo/bar/header1.h') and cppyy.include('foo/bar/header1.h'). I have also tried cppyy.add_include_path('include') and cppyy.add_include_path('include/foo'). Neither of those helped.
Notwithstanding the conclusion in the comments above, the following is for future reference to aid debugging in case someone stumbles on this question with the same problem. To print the full set of include directories as seen by Cling, do: import cppyy print(cppyy.gbl.gInterpreter.GetIncludePath()) It will show as a range of -I<dir> arguments, just as would be given to a C++ compiler on the command line. Paths in the <dir> part of each can be both absolute or relative. If any relative paths are present, Cling will consider them from the current directory of the process, so a basic os.getcwd() will do to retrieve it and os.chdir() can be used to change it. If at any time during the program run the current working directory could change unexpectedly, then I recommend making all paths as given to Cling absolute (or include all relevant headers immediately). For example: cppyy.add_include_path(os.path.abspath('include'))
69,185,735
69,190,195
Why do we need to check the return value of malloc in C, but not new in C++?
There is a thing that I don't understand in C++. To contrast, in C when we call malloc we check if the allocation failed to then free all the previously allocated memory so as to make a clean exit without memory leaks. But in C++ no one seems to care about that with the new operator. I know that it throws std::bad_alloc on failure, but if there were previous successful allocations with new we are left with memory leaks upon a thrown exception, aren't we? In my example the memory leaks are still reachable, but it could be some definitely lost memory. int main(void) { int *ptr1 = new int; int *ptr2 = new int; // do something with ptrs delete ptr1; delete ptr2; return (EXIT_SUCCESS); } Whereas in C we'd do #include <stdlib.h> int main(void) { void *ptr1; void *ptr2; if (!(ptr1 = malloc(10))) return (EXIT_FAILURE); if (!(ptr2 = malloc(10))) { free(ptr1); return (EXIT_FAILURE); } //do something with ptrs free(ptr1); free(ptr2); return (EXIT_SUCCESS); } So shouldn't we do something like this instead given std::bad_alloc can be thrown? #include <new> int main(void) { int *ptr1 = new int; int *ptr2; try { ptr2 = new int; } catch (std::bad_alloc &e) { // do something with exception delete ptr1; return (EXIT_FAILURE); } // do something with ptrs delete ptr1; delete ptr2; return (EXIT_SUCCESS); }
But in C++ no one seems to care about that with the new operator. I know that it throws std::bad_alloc on failure, but if there were previous successful allocations with new we are left with memory leaks upon a thrown exception, aren't we? Only if you're writing very bad C++, in which case you should stop that. This, for example: { int *ptr1 = new int; int *ptr2 = new int; // do something with ptrs delete ptr1; delete ptr2; } is terrible style. No reputable reference would suggest you write this. It is essentially C with different keywords, and adding exceptions to C is not an improvement. So shouldn't we do something like this instead ... No, the following is also bad (although it is more like Java written in C++ than C written in C++) { int *ptr1 = new int; int *ptr2; try { ptr2 = new int; } catch (std::bad_alloc &e) { delete ptr1; return; } // do something with ptrs delete ptr1; delete ptr2; } The usual recommendations (for example, per the Core Guidelines) are: don't use dynamic allocation in the first place unless you really need it (of course we'll assume you're just simplifying something that really did need new/delete, but the code as shown should just use automatic locals instead) if you must have dynamic allocation, use RAII and never owning raw pointers so the correct version of your original code is { auto ptr1 = std::make_unique<int>(); auto ptr2 = std::make_unique<int>(); // do something with ptrs } which is actually less complex, as well as being perfectly correct.
69,185,909
69,239,894
EasyHook stop catching some messages
As soon EasyHook EasyHook64.dll intercepts the first DefWindowProcW message, and from it starts a thread, it does not catch any DefWindowProcW anymore: |___ DefWindowProcW (caught) |-- |-- |-- |-- DefWindowProcW (don't 'intercept' anymore) |-- ... It stops 'catching' all DefWindowProcW messages until the thread end. I was told: This is by design, it is part of the thread deadlock barrier. And: You could install two hooks for the same function, leaving the second disabled until you enter your first hook, you would enable it by setting its ACL inclusive to the current thread, then disable it again as you leave the first hook. Then I tried to call it like: HOOK_TRACE_INFO hHook = { NULL }; HOOK_TRACE_INFO hHook2 = { NULL }; HOOK_TRACE_INFO hHook3 = { NULL }; LRESULT __stdcall DefWindowProcW_Hook( HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam) { switch (Msg) { //...... } ULONG ACLEntries[1] = { 0 }; LhSetInclusiveACL(ACLEntries, 1, &hHook); ULONG ACLEntries2[1] = { 0 }; LhSetInclusiveACL(ACLEntries2, 1, &hHook2); ULONG ACLEntries3[1] = { 0 }; LhSetInclusiveACL(ACLEntries2, 1, &hHook3); return DefWindowProcW(hWnd, Msg, wParam, lParam); } // ======================================= void __stdcall NativeInjectionEntryPoint(REMOTE_ENTRY_INFO* inRemoteInfo) { LhInstallHook( GetProcAddress(GetModuleHandle(TEXT("user32")), "DefWindowProcW"), DefWindowProcW_Hook, NULL, &hHook); ULONG ACLEntries[1] = { 0 }; LhSetExclusiveACL(ACLEntries4, 1, &hHook); LhInstallHook( GetProcAddress(GetModuleHandle(TEXT("user32")), "DefWindowProcW"), DefWindowProcW_Hook, NULL, &hHook2); LhInstallHook( GetProcAddress(GetModuleHandle(TEXT("user32")), "DefWindowProcW"), DefWindowProcW_Hook, NULL, &hHook3); } But now, looks like all hooks are doing the same thing: Result: Would like to ask someone who uses or already used EasyHook how to properly read the same function when there is a 2nd or more nested call.
There is no elegant solution for this in EasyHook, however if you are happy to install as many intermediate hooks as you need for the nesting levels you can chain them together. The outermost hook will be the only one enabled initially. It will first ensure all innermost hooks are disabled, then enable the next hook. To prevent calling the hook for the same DefWindowProcW call, we can retrieve the next hook's bypass address and call that instead of the original DefWindowProcW like you would normally do. As you have already discovered, once within a hook handler for a hook it will not trigger that same hook again until after the return statement has completed and we have gone back up the call stack. This is due to the thread-deadlock barrier in EasyHook. Example: HOOK_TRACE_INFO hHook = { NULL }; HOOK_TRACE_INFO hHook2 = { NULL }; HOOK_TRACE_INFO hHook3 = { NULL }; typedef LRESULT __stdcall DefWindowProcFunc(HWND, UINT, WPARAM, LPARAM); // Innermost hook handler LRESULT __stdcall DefWindowProcW_Hook( HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam) { switch (Msg) { //...... } // Innermost hook just call original return DefWindowProcW(hWnd, Msg, wParam, lParam); } // Middle hook handler LRESULT __stdcall DefWindowProcW_Hook2( HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam) { switch (Msg) { //...... } // Activate next hook handler for next nesting level ULONG ACLEntries[1] = { 0 }; LhSetInclusiveACL(ACLEntries, 1, &hHook); PVOID* bypass_address; LhGetHookBypassAddress(&hHook, &bypass_address); //return DefWindowProcW(hWnd, Msg, wParam, lParam); // Bypass the handler for THIS call to DefWindowProcW - the next nested call will be captured in DefWindowProcW_Hook return ((DefWindowProcFunc*)bypass_address)(hWnd, Msg, wParam, lParam); } // Outermost hook handler LRESULT __stdcall DefWindowProcW_Hook3( HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam) { // Outermost hook handler - this will be called first for new calls to DefWindowProcW switch (Msg) { //...... } // Disable innermost hook(s) - do this for each inner hook that isn't the next hook ULONG disableACLEntries[1] = { 0 }; LhSetExclusiveACL(disableACLEntries, 1, &hHook); // Activate next hook handler for first nesting level ULONG ACLEntries[1] = { 0 }; LhSetInclusiveACL(ACLEntries, 1, &hHook2); PVOID* bypass_address; LhGetHookBypassAddress(&hHook2, &bypass_address); //return DefWindowProcW(hWnd, Msg, wParam, lParam); // Bypass the handler for THIS call to DefWindowProcW - the next nested call will be captured in DefWindowProcW_Hook2 return ((DefWindowProcFunc*)bypass_address)(hWnd, Msg, wParam, lParam); } // ======================================= void __stdcall NativeInjectionEntryPoint(REMOTE_ENTRY_INFO* inRemoteInfo) { // NOTE: the last installed hook handler will be the first called i.e. hHook3, then hHook2 then hHook. LhInstallHook( GetProcAddress(GetModuleHandle(TEXT("user32")), "DefWindowProcW"), DefWindowProcW_Hook, NULL, &hHook); LhInstallHook( GetProcAddress(GetModuleHandle(TEXT("user32")), "DefWindowProcW"), DefWindowProcW_Hook2, NULL, &hHook2); LhInstallHook( GetProcAddress(GetModuleHandle(TEXT("user32")), "DefWindowProcW"), DefWindowProcW_Hook3, NULL, &hHook3); // Activate outermost hook (ie last installed hook which will be the first called - hHook3) ULONG ACLEntries[1] = { 0 }; LhSetExclusiveACL(ACLEntries, 1, &hHook3); }
69,186,023
69,200,905
Clion `cout` and `cin` combination causes console to not work properly
I've recently started trying out CLion for C++ programming. I wanted to test a sample application (below): #include <iostream> int main() { std::cout << "Please enter a number: "; int x; std::cin >> x; std::cout << "Your number was " << x << "!\n"; return 0; } This is what I was expecting (the number is user input): Please enter a number: 10 Your number was 10! And this is exactly what happens when I compile and run manually (g++ main.cpp -o main && ./main) However, this is what happens when I run with CLion: Does anyone know why this is happening, and how I can fix this? Note: I am using CLion with the g++ compiler (version 9.3.0) on WSL2
After some more searching, I came across this StackOverflow post, which led me to this issue (upvote it!) which finally led me to do what was told in the comments: Two workarounds are available: Turn off PTY: by disabling run.processes.with.pty option in the Registry (Help -> Find Action -> Registry...) Use Cygwin64 instead I did the first option and CLion works fine now: It looks like this is an issue with MinGW and WSL.
69,186,171
69,188,285
Get all N consecutive characters in string using stringstream in C++
I would like something that can window a std::string object into partitions of length N - for example (using a function update): int main() { std::string s = "abcdefg"; update<2>(s); return 0; } Calling the above should result in: ab bc cd ef fg I have the following version of the update function: template<std::size_t size> void update(std::string s) { std::string result(size, '\0'); std::stringstream ss{s}; int iterations = s.length() - size; for (int i = 0; i<iterations; i++) { ss.read(&result[0], result.size()); std::cout << result << std::endl; } return; } but this skips out combinations where the initial character lies at an odd index (the number of combinations is correct in my case, even though there is a repeat) ab cd ef gf gf A side note is that if there are any trailing characters then these should be omitted from the printed values (although I think this would be covered by the parameters of the for loop) A final note is that I would like this to be as optimised as possible since I would typically be using strings of a very large length (>5M characters long) - my current solution may not be best for this so I am open to suggestions of alternative strategies.
With C++17 you can do it like this, which is way more readable: void update(std::string_view s, int size) { const int iterations = s.size() - size; for (int i = 0; i <= iterations; i++) { std::cout << s.substr(i, size) << "\n"; } } string_view is made exactly for this purpose, for fast read access to a string. string_view::substr is const complexity while string::substr is linear. As a side note, besides what Nick mentioned, your code has few other small problems: std::endl fflushes the stream, it heavily impacts performance. Here you could just use '\n' to make a newline. the return at the end is absolutely redundant, void functions do not require returns what is the purpose of templating this? This will easily bloat your code without any measurable performance increase. Just pass the N as a parameter. also your main is declared as void and should be int (even more so as you do return a value at the end)
69,186,185
69,186,229
Issue with variadic template template parameter pack
Consider the following example: template< class A, int B, class C> struct Obj { A a_obj; static constexpr int b_value = B; C c_obj; }; template< template<class... > class ... Templates > struct Foo; template<> struct Foo<Obj> { Obj<void*, 5, float> obj; }; int main() { Foo<Obj> foo; }; This is failing on me (g++ 7.2, with -std=c++17 with the following errors: templ.cpp:16:15: error: type/value mismatch at argument 1 in template parameter list for ‘template<template<class ...> class ... Templates> struct Foo’ 16 | struct Foo<Obj> { | ^ templ.cpp:16:15: note: expected a template of type ‘template<class ...> class ... Templates’, got ‘template<class A, int B, class C> struct Obj’ templ.cpp: In function ‘int main()’: templ.cpp:23:8: error: type/value mismatch at argument 1 in template parameter list for ‘template<template<class ...> class ... Templates> struct Foo’ 23 | Foo<Obj> foo; | ^ templ.cpp:23:8: note: expected a template of type ‘template<class ...> class ... Templates’, got ‘template<class A, int B, class C> struct Obj’ It seems that it is not getting matched, although it doesn't look like it thinks the template<class ...> class ... Templates is a syntax error, hence the parameter-parameter pack is parsing Is this type of declaration (with some types, a constant value, then more types, or perhaps constant values at the end) unmatchable with variadic template template pack syntax? or perhaps I'm not using the syntax right Edit I modified the version to avoid non-types in declarations, but the problem persists: template< template <class, class> class B, class A, class C> struct Obj { A a_obj; //static constexpr int b_value = B; B< C, A > b_obj; C c_obj; }; template< template<typename... > typename ... Templates > struct Foo; template<class A, class V> struct Bar { A a_obj; //static constexpr int value = V; V obj; }; template<> struct Foo<Obj> { Obj<Bar, void*, float> obj; }; int main() { Foo<Obj> foo; }; So it seems that is not that just non-types and types cannot be matches on a variadic pack, but any mixture of types and templates I also tried adding an additional variadic pack: template< template<typename... > typename ... Templates, class ... Types > struct Foo; But then I get: error: parameter pack ‘template<class ...> class ... Templates’ must be at the end of the template parameter list 12 | template< template<typename... > typename ... Templates, class ... Types >
int B is a non-type template parameter. You have to declare Templates as template<class, auto, class> class if you want it to work with that particular class template, or redefine Obj to take a std::integral_constant to pass a value encapsulated in a type: template<class A, class B, class C> struct Obj { A a_obj; static constexpr int b_value = B::value; C c_obj; }; template<template<class...> class... Templates> struct Foo; template<> struct Foo<Obj> { Obj<void*, std::integral_constant<int, 5>, float> obj; }; int main() { Foo<Obj> foo; } Try it on godbolt.org.
69,186,440
69,188,796
Using a signal listener thread - how do I stop it?
A snippet from my main method: std::atomic_bool runflag; // ... std::thread signaller([&]() mutable { while (runflag) { int sig; int rcode = sigwait(&set, &sig); if (rcode == 0) { switch (sig) { case SIGINT: { // handle ^C } } } } }); while (runflag) { next = cin.get(); // handle character input } signaller.join(); I'm using the sigwait()-based approach for detecting SIGINT sent from the command line. The signaller thread uses sigwait() to listen for signals. The program terminates when runflag is set false. However, the signaller thread will still be blocked at sigwait when this happens. I don't think I can use condition variables, as sigwait has no way to hook into one. Is there an alternative solution that is preferably not Linux-only? EDIT 1: Alternatively, is there an interruptible version of sigwait?
You can use the sigtimedwait() function, which returns after a timeout given as a parameter. You will need to check the return value from sigtimedwait() to check if it finished because of timeout or the signal arrived and then depending on this value you will need to handle signal or just check runflag and run again sigtimedwait(). Here is more about it from another answer: https://stackoverflow.com/a/58834251/11424134
69,186,560
69,187,368
Mergesort not working as intended with linked list
Preface: I do not care about the viability of my particular merge sort algorithm. That is not what the question is about. I am curious as to why the program I have already written behaves the way it does, not about why I should use the STL or whatever. This is for learning purposes. Question: I have a linked list struct composed of Node*s. I've written up a semi-recursive merge sort algorithm (I say semi because the actual sorting is iterative technically) for this particular structure, and it doesn't quite work the way it should (sort ascending). When walking through the code with a debugger, it appears the actual sorting function merge() doesn't retain the newly sorted list throughout calls, and I cannot wrap my brain around how to do that. Could someone explain? Here is a minimal reproducible example: #include <iostream> struct Link { Link(int d=int(), Link* n=nullptr) { data = d; next = n; } int data; Link* next; }; struct LinkList { Link* sentinel; size_t size; LinkList(Link* h=new Link, size_t s=0) { size = s; sentinel = h; } ~LinkList() { Link* current = sentinel; while (current != 0) { Link* next = current->next; delete current; current = next; } sentinel = 0; } }; // split into beg and end subLinkList using f/s ptr algorithm void split(Link* sentinel, Link*& beg, Link*& end) { Link* s = sentinel, * f = sentinel->next; while (f != NULL) { f = f->next; if (f != NULL) { s = s->next; f = f->next; } } beg = sentinel; end = s->next; s->next = NULL; } // conquer (merge) elements from both subLinkLists into new sentinel Link* merge(Link* beg, Link* end) { Link* sentinel = new Link; Link* tmp; for (tmp = sentinel; beg != NULL && end != NULL; tmp = tmp->next) { if (beg-> data < end->data) { tmp->next = beg; beg = beg->next; } else { tmp->next = end; end = end->next; } } if (beg == NULL) tmp->next = end; else tmp->next = beg; return tmp; } // recursive splitting and merging Link* sort_merge(Link* sentinel) { Link* beg, * end; if (sentinel == NULL || sentinel->next == NULL) return sentinel; split(sentinel, beg, end); sort_merge(beg); sort_merge(end); return merge(beg, end); } // helper function calls sort_merge void sort(LinkList &l) { sort_merge(l.sentinel); } void print(LinkList &l) { for (Link* n = l.sentinel; n != NULL; n = n->next) { std::cout << n->data << '\n'; } } int main() { // set up linked LinkList 5->4->3->2->1->nullptr Link* sentinel = new Link(5 , new Link(4, new Link(3, new Link(2, new Link(1))))); LinkList l(sentinel,5); sort(l); print(l); return 0; } The output I want to have is 1 2 3 4 5 but it outputs 5
A few issues: merge returns the last node of merged list instead of the first. So change: return tmp; to: return head->next; In msort the return value of the recursive call is ignored, but it is important, as it represents the first node after the sort operation. So change: msort(left); msort(right); to: left = msort(left); right = msort(right); In sort the return value of msort is ignored so that the head reference of the list is never updated. So change: msort(l.head); to: l.head = msort(l.head);
69,186,891
69,186,939
Why does std::regex_match generate different results
I'm trying to use std::regex to validate some variables from a file in my c++11 project. For now I need to validate if a string is a valid URL or not. Here is my code: https://godbolt.org/z/4Pn9eYEce As you see, it works as expected. It returns a true. However, when I run the same code on my server, it returns a false. I really don't know why. My server is Ubuntu 16.04.4 LTS, and the version of GCC is 5.4.0 20160609 (Ubuntu 5.4.0-6ubuntu1~16.04.11).
Must be a compiler thing, compiling on gcc5.4 with -Wformat -std=c++17, and then running it also returns 0. https://godbolt.org/z/a8o9x9nWP Probably best if you update your compiler to a newer version.
69,187,604
69,187,727
C++ Nesting SFINAE Template Produces Compilation Error
I'm trying to create an addition operator for a custom template class, where the first argument is allowed to be either an instance of my class or a basic numeric type. My operator has a definition similar to the example code below: #include <type_traits> template<typename T> struct MyTemplateStruct { T val; }; template<typename T, typename U> struct MyCommonType { typedef std::common_type_t<T, U> type; }; template<typename T, typename U> using MyCommonTypeT = typename MyCommonType<T, U>::type; template<typename T, typename U> MyTemplateStruct<MyCommonTypeT<T, U>> operator +( MyTemplateStruct<T> const& a, MyTemplateStruct<U> const& b) { return { a.val + b.val }; } template<typename T, typename U> MyTemplateStruct<MyCommonTypeT<T, U>> operator +( T const a, MyTemplateStruct<U> const& b) { return { a + b.val }; } int main() { MyTemplateStruct<double> a{ 0 }, b{ 0 }; a = a + b; return 0; } My expectation was that due to SFINAE, the compilation error that results from trying to instantiate the second operator definition with T = MyTemplateStruct<double>, U = double would just exclude that template from the list of potential matches. However, when I compile, I'm getting the following error: /usr/include/c++/7/type_traits: In substitution of ‘template<class ... _Tp> using common_type_t = typename std::common_type::type [with _Tp = {MyTemplateStruct, double}]’: main.cpp:18:38: required from ‘struct MyCommonType<MyTemplateStruct, double>’ main.cpp:31:39: required by substitution of ‘template<class T, class U> MyTemplateStruct<typename MyCommonType<T, U>::type> operator+(T, const MyTemplateStruct&) [with T = MyTemplateStruct; U = double]’ main.cpp:40:13: required from here /usr/include/c++/7/type_traits:2484:61: error: no type named ‘type’ in ‘struct std::common_type, double>’ If I directly utilize std::common_type_t in the operator definition, instead of using my wrapper template MyCommonTypeT, then SFINAE works as I expect and there is no error. How can I make the above code compile when I have to wrap the call to std::common_type in another template?
You need to make MyCommonTypeT<T, U> (i.e. MyCommonType<T, U>::type) itself invalid, it's not enough that std::common_type_t<T, U> is invalid when declaring type in MyCommonType. For example you can specialize MyCommonType, when MyTemplateStruct is specified as template argument, type is not declared. template<typename T, typename U> struct MyCommonType { typedef std::common_type_t<T, U> type; }; template<typename T, typename U> struct MyCommonType<MyTemplateStruct<T>, U> {}; template<typename T, typename U> struct MyCommonType<T, MyTemplateStruct<U>> {}; LIVE
69,188,266
69,188,715
Cumulative product of an array: std::accumulate vs loop
Let's say I want to compute the cumulative product of the first k elements of an array. int arr[8] = {3, 5, 7, 4, 8, 9, 1, 2}; int k = 3; Which one is the best option in terms of performance? Option 1. Ordinary for loop int result = 1; for (size_t i = 0; i < k; ++i) { result *= arr[i]; } Option 2. Accumulate result = std::accumulate(std::begin(arr), std::begin(arr) + k, 1, [](const int& x, const int &y) { return x*y; }); I am especially interested in cases where k is small, for example k = 3 or k = 4. Is the fancy C++11 way of doing things actually worth it in this case?
Both approaches are fine; neither is bad. The choice between them is matter of opinion. The latter is hardly "fancy C++11", since the only meaningful C++11 feature used is the lambda which can be replaced with std::multiplies or in general case with a function object in "fancy C++98". (Yes std::begin was added in C++11 as well, but you can simply remove it as it isn't necessary). I want to suggest a ranges alternative. Unfortunately C++20 didn't include std::ranges::accumulate, so I have to suggest using a non-standard algorithm instead: std::ranges::subrange sub1(arr, arr + k); auto sub2 = std::views::counted(arr, k); // alternative std::span sub3(arr, k); // less general alternative // no standard ranges alternative for this yet auto result = ranges::accumulate(sub1, 1, std::multiplies<>{}); Which one is the best option in terms of performance? Both/neither. Any decent optimiser should produce identical assembly.
69,188,984
69,189,158
How to change value of array using pointer?
I am making a program which asks user for input and then separates it from comma and adds all separated values to an array. But as you can see, when I print the first value of the array, it doesnt print anything. Im a beginner. #include <iostream> #include <string> #include "Header.h" #include "Windows.h" #include <array> void Seperate(std::string input, std::string(*ptr)[50]) { if (input[input.length() - 1] == ',') { input.erase(input.length() - 1, 1); } std::string value; int length = input.length(); for (int i = 0; i < length; i++) { if (input[i] != ',') { value += input[i]; } else { (*ptr)[i] = value; value = ""; } } } int main() { std::cout << "Enter comma seperated values to seperate: "; std::string input; std::cin >> input; std::string list[50]; std::string(*ptr)[50] = &list; Seperate(input, ptr); std::cout << list[0]; }
On this part you should use another int value to set your pointer values : else { (*ptr)[i] = value; value = ""; } This should work for you like this : std::string value; int length = input.length(); int j = 0; for (int i = 0; i < length; i++) { if (input[i] != ',') { value += input[i]; } else { (*ptr)[j] = value; j = j + 1; value = ""; } }
69,189,157
69,189,206
PX4 Multi-Vehicle Simulation with Gazebo : What is No ROS?
https://docs.px4.io/master/en/simulation/multi_vehicle_simulation_gazebo.html What is the meaning of No ROS in that link and what is the difference between No ROS and simulation with ROS?
The text at the very top of the page explains that they use different commands depending on whether you are using ROS or not. A different approach is used for simulation with and without ROS. There is a separate section further down about how to do the same thing with ROS.
69,190,349
69,190,668
Pass data from object in class A to class B
New to classes and objects in c++ and trying to learn a few basics I have the class TStudent in which the Name, Surname and Age of student are stored, also I have the constructor which is accessed in main and inserts in the data. What I want to do is: having the class TRegistru, I have to add my objects data in it, in a way that I can store it there, then I could save the data in data.bin and free the memory from the data, then I want to put the data back in the class and print it out. The question is: In what way & what is the best way to add my objects in the second class, so that I could eventually work with them in the way I've described in the comments, so that I won't have to change nothing in main Here's my code so far: #include <iostream> using namespace std; class TStudent { public: string Name, Surname; int Age; TStudent(string name, string surname, int age) { Name = name; Surname = surname; Age = age; cout <<"\n"; } }; class TRegistru : public TStudent { public: Tregistru() }; int main() { TStudent student1("Simion", "Neculae", 21); TStudent student2("Elena", "Oprea", 21); TRegistru registru(student1);//initialising the object registru.add(student2);//adding another one to `registru` registru.saving("data.bin")//saving the data in a file registru.deletion();//freeing the TRegistru memory registru.insertion("data.bin");//inserting the data back it registru.introduction();//printing it return 0; }
Hence the question is about passing data from A to B, I will not comment on the file handling portion. This can be done in multiple ways, but here is one of the simplest and most generic. By calling TRegistru::toString() you serialize every TStudent added to TRegistru into a single string which then can be easily written to a file. Demo class TStudent { public: std::string Name, Surname; int Age; std::string toString() const { return Name + ";" + Surname + ";" + to_string(Age); } }; class TRegistru { public: void add(const TStudent& student) { students.push_back(student); } void deletion() { students.clear(); } std::string toString() const { std::string ret{}; for(const auto& student : students) { ret += student.toString() + "\n"; } return ret; } std::vector<TStudent> students; };
69,190,364
69,190,542
Looping back near the beggining using std::vector iterators
I have an iterator that needs to loop near the beginning of the vector whenever it reaches its end, for the amount it went over the end, like so: std::vector<int> vec = {...}, vec1; std::vector<int>::iterator it = vec.begin(); for(;vec.size() != 0;){ it += k; //k is a const integer if(it >= vec.end()){ it -= items.end(); // something like that, but this syntax is obviously invalid } vec1.push_back(*it); it = vec.erase(it); } So perhaps I increment vec{1,2,3,4,5} by 3, it should first remove 3, then 1 and put them in vec1, in a sense it loops around by however was left when it reached the end. I tried a bunch of different syntaxes, but there's always a type mismatch error. Is there an elegant way of doing this?
XY-solution: I recommend keeping an index instead of an iterator and use the remainder operator. for(std::size_t i = 0; vec.size() != 0;){ i = (i + k) % vec.size(); vec1.push_back(vec[i]); vec.erase(vec.begin() + i); } So perhaps I increment vec{1,2,3,4,5} by 3, it should first remove 3 This doesn't match your attempted code. If you increment iterator to first element by 3 and erase it, then you'd be erasing the element with value 4.
69,190,488
69,192,221
IContextMenu::QueryContextMenu not called by Shell (Win10)
I have a class called ValidatorContextMenuHandler that implements the IShellExtInit and IContextMenu interfaces. My DLL is being referenced in the Registry, and gets loaded into Windows Explorer correctly. I check this by creating MessageBoxes whenever a method is being called. When I right click on a file, I also get notified of my ContextMenuHandler being instantiated. So, IShellExtInit::Initialize() is indeed being called (twice, actually). My implementation of IShellExtInit::Initialize() looks like the following: IFACEMETHODIMP ValidatorContextMenuHandler::Initialize(PCIDLIST_ABSOLUTE pidlFolder, IDataObject* pdtobj, HKEY hKeyProgID) { MessageBox(NULL, L"ContextMenuHandler Initialized!", L"Notice", MB_OK); return S_OK; } However, after that nothing happens. IContextMenu::QueryContextMenu() is never being called, and I cannot find the cause. The first line of QueryContextMenu() should bring up a MessageBox, but it never gets to that point in the first place. My implementation of the method looks like the following: STDMETHODIMP ValidatorContextMenuHandler::QueryContextMenu(HMENU hMenu, UINT indexMenu, UINT idCmdFirst, UINT idCmdLast, UINT uFlags) { MessageBox(NULL, L"QUERYING CONTEXT MENU", L"ValidatorContextMenuHandler::QueryContextMenu()", MB_OK); //...Removed the unnecessary code after this, so that the post doesn't get too long } There are no compiling errors, and the DLL I tested on is the newest version (unloaded DLL with regsvr32 /u, restarted Windows Explorer, loaded DLL with regsvr32). For those wanting to see my header file: #pragma once #include<Windows.h> #include<ShlObj.h> extern UINT g_cObjCount; class ValidatorContextMenuHandler : public IShellExtInit, IContextMenu { protected: DWORD m_ObjRefCount; ~ValidatorContextMenuHandler(); public: ValidatorContextMenuHandler(); //IUnknown Methods ULONG __stdcall AddRef(); ULONG __stdcall Release(); HRESULT __stdcall QueryInterface(REFIID riid, void** ppvObject); //IShellExtInit Methods IFACEMETHODIMP Initialize(PCIDLIST_ABSOLUTE pidlFolder, IDataObject* pdtobj, HKEY hKeyProgID); //IContextMenu Methods IFACEMETHODIMP GetCommandString(UINT_PTR idCmd, UINT uFlags, UINT* pwReserved, LPSTR pszName, UINT cchMax); STDMETHODIMP InvokeCommand(LPCMINVOKECOMMANDINFO pici); STDMETHODIMP QueryContextMenu(HMENU hMenu, UINT indexMenu, UINT idCmdFirst, UINT idCmdLast, UINT uFlags); };
I found out why it wasn't working. A lot of frustration for nothing. In my ValidatorContextMenuHandler.cpp file, I did a simple mistake. When queried for the IContextMenu interface, I accidentally cast this to IClassFactory when I should cast it to IContextMenu. Mistyped it. Before: else if (IsEqualIID(riid, IID_IContextMenu)) { *ppvObject = (IClassFactory*)this; this->AddRef(); return S_OK; } After: else if (IsEqualIID(riid, IID_IContextMenu)) { *ppvObject = (IContextMenu*)this; this->AddRef(); return S_OK; }
69,190,783
69,193,688
Pass templated parameter pack to callback function (also a templated function)
Currently in my code I have a function, that takes various arguments, and a callback object (which is instance of a simple class with a Callback(void) function). This works perfectly fine now, but it clutters code because I have quite a few of these classes, and in most of them their variables are used only by the Callback() function. I would like to replace the classes with simple function like so: #include <iostream> #include <string> template<class T> class TestClass { public: template<typename ...TArgs> using CallbackFuncType = bool(T &Data, TArgs && ...Args); TestClass(const T &Data) : data(Data) {} template<typename ...TArgs> bool Function( CallbackFuncType<TArgs...> Callback, TArgs && ...Args ) { return Callback(data, std::forward<TArgs>(Args)...); } private: const T data; }; struct DataType { int valInt; double valFloat; std::string ToString() { return std::string( "valInt: " + std::to_string(valInt) + "valFloat: " + std::to_string(valFloat) ); } }; bool CBFunction1(DataType &Data, int Arg0, const std::string &Arg1) { std::cout << "Data :" << Data.ToString() << std::endl; std::cout << "CBFunction1: " << "Arg0 : " << Arg0 << "Arg1: " << Arg1 << std::endl; return true; } bool CBFunction2(DataType &Data, int Arg0, double Arg1, const std::string &Arg2) { std::cout << "Data :" << Data.ToString() << std::endl; std::cout << "CBFunction2: " << "Arg0 : " << Arg0 << "Arg1: " << Arg0 << "Arg2: " << Arg2 << std::endl; return true; } int main() { DataType data; data.valInt = 1; data.valFloat = 1.2; TestClass<DataType> testObj(data); std::cout << "test" << std::endl; std::cout << "call CBFunction1" << std::endl; bool val1 = testObj.Function(CBFunction1, 11, "test_string"); bool val2 = testObj.Function(CBFunction2, 11, 111.111, "test_string"); return 0; } Upon compilation I get the following errors: 1>main.cpp 1>main.cpp(75,24): error C2672: 'TestClass<DataType>::Function': no matching overloaded function found 1>main.cpp(75,64): error C2784: 'bool TestClass<DataType>::Function(bool (__cdecl *)(T &,TArgs &&...),TArgs &&...)': could not deduce template argument for 'bool (__cdecl *)(T &,TArgs &&...)' from 'bool (DataType &,int,const std::string &)' 1> with 1> [ 1> T=DataType 1> ] 1>main.cpp(13): message : see declaration of 'TestClass<DataType>::Function' 1>main.cpp(76,24): error C2672: 'TestClass<DataType>::Function': no matching overloaded function found 1>main.cpp(76,73): error C2784: 'bool TestClass<DataType>::Function(bool (__cdecl *)(T &,TArgs &&...),TArgs &&...)': could not deduce template argument for 'bool (__cdecl *)(T &,TArgs &&...)' from 'bool (DataType &,int,double,const std::string &)' 1> with 1> [ 1> T=DataType 1> ] 1>main.cpp(13): message : see declaration of 'TestClass<DataType>::Function' I tried to add type_identity_t to Args, but had no success.
template <typename... TArgs> bool Function(CallbackFuncType<TArgs...> Callback, TArgs&&... Args) Have several issues, the main one is that TArgs should be deduced exactly identically in both place. Issue with template <typename... TArgs> using CallbackFuncType = bool(T& Data, TArgs&&... Args); is that it can only match function with argument which are (l or r value) reference. So something like template <typename... TArgs> using CallbackFuncType = bool(T&, TArgs...); template <typename... TArgs, typename... Ts> bool Function(CallbackFuncType<TArgs...>* Callback, Ts&& ...Args) { return Callback(data, std::forward<Ts>(Args)...); } would fix the issue, but even simpler (and more generic) template <typename Func, typename... Ts> bool Function(Func Callback, Ts&& ...Args) { return Callback(data, std::forward<Ts>(Args)...); } Demo
69,191,069
69,191,115
How can I initialize an array in C++ with a size that is given to the constructor?
I have a C++ class with a member that is supposed to be a two dimensional array. I want to declare my array as a member in the header file of the class. Then in the constructor of my class I want to initialize my array with a size (given to the constructor) and fill it with zeros. I have a working example of what I want in java: class Obj { int[][] array; public Obj(int sizex, int sizey) { array = new int[sizex][sizey]; } } public class Main { public static void main(String[] args) { Obj o = new Obj(12,20); } } I do not want to mess with pointers or alloc() and free(). As my class is supposed to be basically a wrapper for this array, I want to keep it simple. I have thought about using std::vector, but as the array is never being resized after its initialization, I feel like vector is a little overpowered... Is there a better way than this: ? #include<vector> class Obj { std::vector<std::vector<int>> array; public: Obj(int xsize, int ysize) { std::vector<std::vector<int>> newArray(xsize, std::vector<int>(ysize, 0)); array = newArray; } }; int main() { Obj o(12,20); }
std::vector is the best match here. (As you said, in most cases raw arrays and pointers could be avoided. Also see How can I efficiently select a Standard Library container in C++11?) And you can initialize the data member directly in member initializer list instead of assigning in the constructor body after default-initialization, e.g. Obj(int xsize, int ysize) : array(xsize, std::vector<int>(ysize, 0)) { }
69,191,363
69,193,867
32-bit malloc() return NULL when opening many threads?
I have a sample C++ program as below: #include <windows.h> #include <stdio.h> int main(int argc, char* argv[]) { void * pointerArr[20000]; int i = 0, j; for (i = 0; i < 20000; i++) { void * pointer = malloc(131125); if (pointer == NULL) { printf("i = %d, out of memory!\n", i); getchar(); break; } pointerArr[i] = pointer; } for (j = 0; j < i; j++) { free(pointerArr[j]); } getchar(); return 0; } When I run it with Visual Studio 32-bit Debug, it will run with following result: The program can use nearly 2Gb of memory before out of memory. This is normal behavior. However, when I adding the code to start Thread inside the for loop as below: #include <windows.h> #include <stdio.h> DWORD WINAPI thread_func(VOID* pInArgs) { Sleep(100000); return 0; } int main(int argc, char* argv[]) { void * pointerArr[20000]; int i = 0, j; for (i = 0; i < 20000; i++) { CreateThread(NULL, 0, thread_func, NULL, 0, NULL); void * pointer = malloc(131125); if (pointer == NULL) { printf("i = %d, out of memory!\n", i); getchar(); break; } pointerArr[i] = pointer; } for (j = 0; j < i; j++) { free(pointerArr[j]); } getchar(); return 0; } The result is as below: The memory is still just around 200Mb but function malloc will return NULL. Could anyone help explain why the program cannot use the memory up to 2Gb before out of memory? Is it mean creating many threads like above will cause memory leak? In my real application, this error occur when I create about 800 threads, the RAM memory at the time "out of memory" is around 300Mb.
As noted in a comment by @macroland, the main thing happening here is that each thread is consuming 1 MiB for its stack (see MSDN CreateThread and Thread Stack Size). You say malloc returns NULL once the total you have directly allocated reaches 200 MB. Since you are allocating 131125 bytes at a time, that is 200 MB / 131125 B = 1525 threads. Their cumulative stack space will be around 1.5 GB. Adding the 200 MB of malloc memory is 1.7 GB, and miscellaneous overhead likely accounts for the rest. So, why does Task Manager not show this? Because the full 1 MiB of thread stack space is not actually allocated (also called committed), rather it is reserved. See VirtualAlloc and the MEM_RESERVE flag. The address space has been reserved for expansion up to 1 MiB, but initially only 64 KiB are allocated, and Task Manager only counts the latter. But reserved memory will not be unilaterally repurposed by malloc until the reservation is lifted, so once it runs out of available address space, it has to return NULL. What tool can show this? I don't know of anything off the shelf (even Process Explorer does not seem show a count of reserved memory). What I have done in the past is write my own little routine that uses VirtualQuery to enumerate the entire address space, including reserved ranges. I recommend you do the same; it's not much code to write, and very handy when coding for 32-bit Windows because the 2 GiB address space gets cramped very easily (DLLs are an obvious reason, but the default malloc also will leave unexpected reservations behind in response to certain allocation patterns even if you free everything). In any case, if you want to create thousands of threads in a 32-bit Windows process, be sure to pass a non-zero value as the dwStackSize parameter to CreateThread, and also pass STACK_SIZE_PARAM_IS_A_RESERVATION as dwCreationFlags. The minimum is 64 KiB, which will be plenty if you avoid recursive algorithms in the threads. Addendum: In a comment, @iinspectable cautions against using thousands of threads, citing Raymond Chen's 2005 blog post Does Windows have a limit of 2000 threads per process?. I agree that doing so is questionable for a variety of reasons; it is not my intent to endorse the practice, rather I'm just explaining one necessary element.
69,191,499
69,191,786
Is possible to get type a child class type from base class?
I need something like this: template <typename T> class A { public: T commonData; TYPEOF_CHILD_CLASS *test(T data) { return new CHILD_CLASS(data); } }; template <typename T> class B : public A<T> { public: T bdata; B(T data) { bdata = data; } }; template <typename T> class C : public A<T> { public: T cdata; C(T data) { cdata = data; } }; int main(int argc, char const *argv[]) { auto a = C<int>(1).test(2); return 0; } Is possible to define TYPEOF_CHILD_CLASS in c++? Before I used D. In D it works with: R (this R) test(T data) { return new R(data); } ... void main() { auto a = new C!A(1).test(2); } It is a template. Does the c++ have a similar method? Maybe can I set type also via a template? Or may be I determine typename via typeid?
Thanks @Some programmer dude @463035818_is_not_a_number. In according to this link it works. template <class T, typename TT> class A { public: TT commonData; T *test(TT data) { return new T(data); } }; template <typename T> class B : public A<B<T>, T> { public: T bdata; B(T data) { bdata = data; } }; template <typename T> class C : public A<C<T>, T> { public: T cdata; C(T data) { cdata = data; } }; int main(int argc, char const *argv[]) { auto a = C<int>(1).test(2); return 0; }
69,191,540
69,191,987
Scope rules of `for` loop different in C++ than in C?
I noticed that the scope rules of the for loop are different for C and C++. For example, the code below is legal in the C compiler, but not legal in the C++ compiler. for (int i = 0; i < 10; ++i) { int i = 5; } The above code is valid in C, but gives a redefinition error in C++. My guess is that the C compiler treats the loop as if there is another scope inside the loop like below. for (int i = 0; i < 10; ++i) { { int i = 5; } } Why does the C compiler allow a second variable with the same name to be defined in the scope of the loop? Is there any particular reason or advantage for doing this?
As far as standards go, for loop scopes are indeed defined differently in C and in C++. In C they are defined as follows: 6.8.5.3 The for statement The statement for ( clause-1 ; expression-2 ; expression-3 ) statement behaves as follows: ... with no specific reference given to limitations on variable declarations inside the statement. The top-level description of loops ("iteration statements" in the standard) specifies: An iteration statement is a block whose scope is a strict subset of the scope of its enclosing block. The loop body is also a block whose scope is a strict subset of the scope of the iteration statement. as you've hinted in your question, code like: for (int i = 0; i < 10; ++i) int i = 5; where a new block is not declared (notice the missing { } surrounding the redeclaration) - is not valid code. Whereas in C++, there is a specific reference to redeclaration of loop variables: 8.6 Iteration statements specify looping ... If a name introduced in an init-statement or for-range-declaration is redeclared in the outermost block of the substatement, the program is ill-formed. As it relates to rationale - likely C++ just added the restriction as an improvement to language semantics, indeed redeclaring a variable this way is usually a bug. Arguably, this restriction is appropriate in C as well - but adding this restriction to the C standard would break backwards compatibility with existing code and is unlikely to happen.
69,192,537
69,194,649
{fmt}: Will a named argument be ignored if it doesn't exist in the formatting string?
The following code compiles just fine and produces the string "abc": fmt::format("abc", fmt::arg("x", 42)); godbolt So it looks like named arguments that are missing in the format string are just ignored. My question is: Is that by design or is it a bug? I'm asking because I'm having a use case for this "feature". So I want to make sure that this is neither UB nor that it will be "fixed" in future. I already skimmed through the docs but couldn't find this use case.
This is by design. Unused formatting arguments are essentially the same as unused arguments to any other function and are not an error. This is the case in {fmt} and Python's str.format it is modeled after as well as printf.
69,192,689
69,194,429
Execution time overhead at index 2^21
What do I want to do? I have written a program which reads data from binary files and does calculation based on the read values. Execution time is most import for this program. To validate that my program is operating within the specified time limits, I tried to log all the calculations by storing them inside a std::vector<std::string>. And after the time critical execution is done, I write this vector to a file. What is stored inside the vector? In the vector I write the execution time (std::chrono:steady_clock.now()) and the current clock time (std::chrono::system_clock::now() with date.h by Howard Hinnant). What did I observe? While analyzing the results I stumble over the following pattern. Independent on the input data the mean execution time of 0.003ms for one operation explodes to ~20ms for a single operation at one specific reproducible index. After this, the execution time of all operations goes back to 0.003ms. The index of the execution time explosion is every time 2097151. Since 2^21 equals 2097152, something happens at 2^21 that slows down the entire program. The same effect can be observed with 2^22 and 2^23. Even more interesting is that the lag is doubled (2^21 = ~20ms, 2^22 = ~43ms, 2^23 =~81ms ). I googled about this specific number and the only thing I found was some node.js stuff which uses c++ under the hood. What do I suspect? At index 2^21 a memory area must be expanded, and that is why the delay occurs. Questions Is my assumption correct and the size of the vector is the problem? How can I debug such a Phenomenon? (To be certain, that purely the vector is the problem) Can I allocate enough memory beforehand to avoid the memory expansion? What could I use instead of a std::vector, which supports > 10.000.000.000 elements?
I was able to solve my problem by reserving memory by using std::vector::reserve() before the time critical part of my program. Thanks to all the comments. Here the working code I used: std::vector<std::string> myLogVector; myLogVector.reserve(12000000); //...do time critical stuff, without reallocating storage
69,193,300
69,389,108
How much memory(MB) can the vector variable occupy in enclave of Intel sgx?
I want to immigrate PageRank algorithm in the sgx enclave. The algorithm uses vector to save the edge relationship and matrix. vector<size_t> num_outgoing; // number of outgoing links per column vector< vector<size_t> > rows; // the rowns of the hyperlink matrix map<string, size_t> nodes_to_idx; // mapping from string node IDs to numeric map<size_t, string> idx_to_nodes; // mapping from numeric node IDs to string vector<double> pr; // the pagerank table The application runs well when it stores less than 9000 edges. Once it increases to 10000 edges or more, the application crushes, and throws out an unhandled exceptionenter image description here . I also run the same code outside the enclave, it runs well when it stores 90000 edges. By debugging, I found the application fails at the places below. if (rows.size() <= max_dim) { max_dim = max_dim + 1; rows.resize(max_dim); if (num_outgoing.size() <= max_dim) { num_outgoing.resize(max_dim); } } However, the variable 'rows' cannot be resized larger once it owns 13896 element. I'm confused that 'rows' only occupies about 300kb and 'num_outgoing' only occupies about 100kb. It's far less than the allow size. There is 128MB space in total for the enclave application. My enclave config file is listed as follows. I try to change the value of StackMaxSize, however, it seems useless. <EnclaveConfiguration> <ProdID>0</ProdID> <ISVSVN>0</ISVSVN> <StackMaxSize>0x400000</StackMaxSize> <HeapMaxSize>0x100000</HeapMaxSize> <TCSNum>1</TCSNum> <TCSPolicy>1</TCSPolicy> <DisableDebug>0</DisableDebug> <MiscSelect>0</MiscSelect> <MiscMask>0xFFFFFFFF</MiscMask> <EnableKSS>0</EnableKSS> <ISVEXTPRODID_H>0</ISVEXTPRODID_H> <ISVEXTPRODID_L>0</ISVEXTPRODID_L> <ISVFAMILYID_H>0</ISVFAMILYID_H> <ISVFAMILYID_L>0</ISVFAMILYID_L> </EnclaveConfiguration> The format of the input edge is shown as below. The first number is the "from" node, the second number is the "to" node 1 0 2 0 3 1 4 3 5 4 6 0 7 1 8 0 9 1 10 0 I wonder how to config enclave to make it allow bigger vector variable? The problem exists on both win10 and ubuntu.
All seems like you are running out of memory. The memory limits (stack and heap) are set in the config file using StackMaxSize and HeapMaxSize (see Developer Reference for details). The size of the EPC (128MB or 256MB) has nothing to do with it. Here, you are not bounded by the EPC size but by the heap and stack. Increasing the stack size does not change anything because dynamically allocated memory resides on heap. In turn, you should be looking at the max heap size. Currently, you have it set to 0x100000 (=1MB), which is quickly used up by your data. Try increasing it and see if you can accommodate larger vectors. I think on Windows your enclave has to entirely fit into EPC but on Linux you can create enclaves with tens of GBs. Be aware that once your (Linux) enclave memory usage exceeds ~90 MB you will start noticing EPC paging and, with it, a huge performance degradation.
69,193,308
69,193,741
Storing virual functions in Array/Vector container
I have a base class with common behavior and derived classes with override virtual functions. But if tried to save the function pointer as std::vector I will get the error: ISO C++ forbids taking the address of an unqualified or parenthesized non-static member function to form a pointer to member function. I need something like this: class Base { public: virtual int fun1(int inp) = 0; virtual int fun2(int inp) = 0; int init(int inp, std::vector<std::function<int(int)>> Callbacks, int index) { if (index == 0) return Callbacks[0](inp); else return Callbacks[1](inp); } int run() { return init(5, { &fun1, &fun2 }, 0); } }; class A : public Base { int fun1(int inp) { return inp * 10; } int fun1(int inp) { return inp * 100; } }; class B : public Base { int fun1(int inp) { return inp * 20; } int fun2(int inp) { return inp * 200; } }; int main(int argc, char const* argv[]) { auto f = new B; int e = f->run(); return 0; } Is there any way to do what I want? Maybe I can bind a virtual function to a container somehow? Or maybe can I set the lambda function as virtual? When I tried to declare lambda function in the Base class when I change function in derived class I get errors:
You get a "pointer" to a member with the syntax &Class::Member (Class::Member is the "qualified" name of the member). These are pointers only in an abstract sense, and need to be dereferenced relative to an object. You do this with the ->* or .* operator, depending on whether the left-hand side is a pointer or not. Note that you must use this explicitly, if that is the relevant object. The type of &Base::fun1 and &Base::fun2 is int (Base::*)(int), which can't be converted to std::function<int(int)>. Putting it together: int init(int inp, std::vector<int (Base::*)(int)> Callbacks, int index) { if (index == 0) return (this->*Callbacks[0])(inp); // The leftmost parentheses are necessary. else return (this->*Callbacks[1])(inp); } int run() { return init(5, {&Base::fun1, &Base::fun2}, 0); } If you don't want to limit the callbacks to members, you can use lambda functions, capturing this: int init(int inp, std::vector<std::function<int(int))> Callbacks, int index) { if (index == 0) return Callbacks[0](inp); else return Callbacks[1](inp); } int run() { return init(5, {[this](int i) { return fun1(i); }, [](int) { return 567; } }, 0); }
69,193,405
69,193,874
How to find the greatest number among the numbers given input?
I'm a beginner in programming and as you can see, I created a program where the user is asked to input three numbers. It will display the greatest among the numbers given. But after I finished the code, a question came into my mind, what if the user was asked to input a hundreds of numbers and should display the greatest among the numbers given. So the question is, is it possible to do that? what are the things I need to learn to produce that result? is there any hints you can give me? #include <iostream> #include <string> using std::cout, std::cin, std::endl, std::string; int main() { string result = " is the greatest among the numbers given"; double x, y, z; cout<<"Enter three numbers to decide which is the largest: "<<endl; cin >>x; cin >>y; cin >>z; system("clear"); if(x>y && x>z){ cout<< x << result; } else if (y>z && y>x){ cout << y << result; } else cout<< z << result; return 0; }
With the program below, you can get as many numbers as you want from the user and find the largest of them. #include <iostream> int main() { int size=0, largestValue=0, value=0; std::cout << "Enter total numbers you want to add :" << "\n"; std::cin >> size; for (int i{ 0 }; i < size; ++i) { std::cout << "Enter value to add : "; std::cin >> value; if (i == 0 || value > largestValue) { largestValue = value; } } std::cout << "Largest value = " << largestValue << "\n"; return 0; }
69,193,573
69,265,126
Not receiving data in LCP(PPPoS) phase over UART(ESP-32 -> Sim7600)
On my ESP32 I am having trouble creating a working PPP interface to my ISP. I am using an ESP-32 Ethernet kit and have it hooked up to a Simcom EVB Kit with a Sim7600G chip. With this hardware I am using ESP-IDF in combination with LWIP to get the PPP connection going. At first I have to send all the corresponding AT commands to make sure it is actually ready for a PPP connection. These AT Commands are the following: AT+CGDCONT=1,"IP","<APN>" AT+CGACT=1,1 AT+CREG? <Must be 0,5 -> Registered and Roaming> ATD*99***1# -> I receive "Connect 152000" and start the PPP phase. After I received the Connect 152000 as a response, I start the PPP connection. m_pPpp = pppapi_pppos_create(&netif, pppos_output_cb, ppp_link_status_cb, nullptr); pppapi_set_default(m_pPpp); pppapi_set_auth(m_pPpp, PPPAUTHTYPE_PAP, "", ""); err_t err = ppp_connect(m_pPpp, 0); This is the output of the corresponding code: ppp phase changed[2]: phase=0 ppp_connect[2]: holdoff=0 ppp phase changed[2]: phase=3 pppos_connect: unit 2: connecting ppp_start[2] ppp phase changed[2]: phase=6 pppos_send_config[2]: out_accm=FF FF FF FF ppp_send_config[2] pppos_recv_config[2]: in_accm=FF FF FF FF ppp_recv_config[2] ppp: auth protocols: PAP=1 sent [LCP ConfReq id=0x1 <asyncmap 0x0> <magic 0xcd3e2cad> <pcomp> <accomp>] I: pppos_output callback called I: ppp_output_cb() len = 45 W: ip4addr: 0.0.0.0 W: his_ipaddr: 0.0.0.0 W: netmask: 255.255.255.255 pppos_write[2]: len=24 ppp_start[2]: finished As far as I can see, it goes through a couple of phases regarding the PPP connection. Phase 0(dead, obviously) Phase 3(initialize) Phase 6(Establish). It will not continue after this. I see the pppos_output callback is being called, which is supposed to happen. As far as I understand this function is so you can write the PPP-data towards your UART device. Seperately I have a task running in the background to poll my UART device for written data so I can write this to the pppos_input function. I never receive any data... I honestly have no idea where if I am missing something or how to troubleshoot this. Also the LWIP documentation is quite plain and is missing examples, which makes it even harder. Additional things I have tried: AT+CGDCONT=1,"PPP","APN". <- This will result in the Sim7600 never connecting and remains searching. Should I use these PDP settings or stay with IP? Applied the above AT command and tried starting the PPP phase, hoping it would result in somehow connecting...
I have not found the solution to this problem with the mentioned frameworks. Instead I reverted to another dependency from the ESP-IDF: esp-modem. I managed to get a working solution by following the pppos-client and modem-console examples within my current software.
69,193,728
69,194,610
Get Name List of all running processes windows
I want to get list of all running processes like following example.exe example2.exe so on... heres code what ive tried WCHAR* GetAllRunningProccess() { PROCESSENTRY32 pe32; HANDLE snap = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 ); pe32.dwSize = sizeof(PROCESSENTRY32); Process32First(snap, &pe32); do { return pe32.szExeFile; } while (Process32Next(snap, &pe32)); } std::wcout << GetAllRunningProccess() << std::endl; it only prints [System Process]
The code you have written does not work like a generator function to yield multiple values. It just exits when returning the first value. You cannot return from a function more than once. do { return ...; // This will both exit the loop and exit the function. } while(...); Although, coroutines offer co_yield to accomplish this. To fix... The most basic repair would be to redesign your function to return a vector of strings rather than just a single string. std::vector<std::string> GetAllRunningProcesses() { PROCESSENTRY32 pe32; HANDLE snap = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 ); pe32.dwSize = sizeof(PROCESSENTRY32); Process32First(snap, &pe32); std::vector<std::string> result; do { result.push_back(pe32.szExeFile); } while (Process32Next(snap, &pe32)); CloseHandle(snap); return result; } Then, to call it, you could use something like this: for (const auto& processName : GetAllRunningProcesses()) { std::cout << processName << std::endl; }
69,193,825
69,193,929
how delete class variable in struct?
InitMyObject(MyObject* ptr) { *ptr = MyObject(); } struct Data { MyObject obj; }; extern Data data; // ... InitMyObject(&data.obj); delete &data.obj; // ? is this ok How I can delete (call deconstructor) data.obj, I also try Data::obj as pointer (nullptr default) then pass the pointer but crashed on Init.
How I can delete (call deconstructor) data.obj The destructor of data will destroy its subobjects. Since data has static storage, it is automatically destroyed at the end of the program. delete &data.obj; // ? is this ok No. You may only delete the result of a non-placement new expression. You may not delete a pointer to a member object.
69,194,075
69,194,245
Structural tuple-like / Wrapping a variadic set of template parameters values in a struct
I find myself wanting/needing to use a variadic composite type as a template parameter. Unfortunately, std::tuple<> is not a structural type, which makes the obvious approach a no-go: #include <tuple> template<typename... Ts> struct composite { std::tuple<Ts...> operands; }; template<auto v> void foo() {} int main() { constexpr composite tmp{std::make_tuple(1,2,3)}; foo<tmp>(); // <----- Nope! } Is there a reasonable way to build such a composite in a manner that works as a structural type? Since the MCVE in isolation is trivially solvable as "just make foo() a variadic template", here's a more representative example: On godbolt #include <concepts> #include <tuple> template <typename T, template <typename...> typename U> concept TemplatedConfig = requires(T x) { { U(x) } -> std::same_as<T>; // A few more things identifying T as a valid config }; template<auto Config> struct proc; // Basic struct Basic {}; template<Basic v> struct proc<v> { constexpr int foo() { return 0; } }; // Annotated template<typename T> struct Annotated { T v; int annotation; }; template<TemplatedConfig<Annotated> auto v> struct proc<v> { constexpr int foo() { return 1; } }; // ... more config / specialization pairs ... // Composite template<typename... Parts> struct Composite { std::tuple<Parts...> parts; }; template<TemplatedConfig<Composite> auto v> struct proc<v> { constexpr int foo() { return 2; } }; int main() { constexpr Basic a = Basic{}; constexpr Annotated b{a, 12}; constexpr Composite c{std::make_tuple(a, b)}; static_assert(proc<a>{}.foo() == 0); static_assert(proc<b>{}.foo() == 1); static_assert(proc<c>{}.foo() == 2); <----- :( } Edit: If anyone is curious what a (almost) fully-realized tuple class based on the accepted answer looks like: https://gcc.godbolt.org/z/ThaGjbo67
Create your own structural tuple-like class? Something like: template <std::size_t I, typename T> struct tuple_leaf { T data; }; template <typename T> struct tag{ using type = T; }; template <typename Seq, typename...> struct tuple_impl; template <std::size_t... Is, typename... Ts> struct tuple_impl<std::index_sequence<Is...>, Ts...> : tuple_leaf<Is, Ts>... { constexpr tuple_impl(Ts... args) : tuple_leaf<Is, Ts>{args}... {} }; template <typename T, std::size_t I> constexpr const T& get(const tuple_leaf<I, T>& t) { return t.data; } template <typename T, std::size_t I> constexpr T& get(tuple_leaf<I, T>& t) { return t.data; } template <std::size_t I, typename T> constexpr const T& get(const tuple_leaf<I, T>& t) { return t.data; } template <std::size_t I, typename T> constexpr T& get(tuple_leaf<I, T>& t) { return t.data; } template <std::size_t I, typename T> tag<T> tuple_element_tag(const tuple_leaf<I, T>&); template <std::size_t I, typename Tuple> using tuple_element = decltype(tuple_element_tag<I>(std::declval<Tuple>())); template <std::size_t I, typename Tuple> using tuple_element_t = typename tuple_element<I, Tuple>::type; template <typename ... Ts> using tuple = tuple_impl<std::make_index_sequence<sizeof...(Ts)>, Ts...>; Demo
69,194,230
69,194,881
What is the purpose of `operator auto() = delete` in C++?
A class in C++ can define one or several conversion operators. Some of them can be with auto-deduction of resulting type: operator auto. And all compilers allow the programmer to mark any operator as deleted, and operator auto as well. For concrete type the deletion means that an attempt to call such conversion will result in compilation error. But what could be the purpose of operator auto() = delete? Consider an example: struct A { operator auto() = delete; }; struct B : A { operator auto() { return 1; } }; int main() { B b; A a = b; // error in Clang int i = b; // error in Clang and GCC int j = a; // error in Clang and GCC and MSVC } Since the compiler is unable to deduce the resulting type, it actually prohibits any conversion from this class or from derived classes with the error: function 'operator auto' with deduced return type cannot be used before it is defined. Demo: https://gcc.godbolt.org/z/zz77M5zsx Side note that compilers slightly diverge in what conversions are still allowed (e.g. GCC and MSVC permit the conversion to base class), which one of them is right here?
But what could be the purpose of operator auto() = delete? What would be the purpose of the following function? auto f() = delete; As per the grammar functions, [dcl.fct.def.general]/1, the function-body of a function-definition may be = delete; e.g., it is syntactically valid to define a function as deleted. C++14 introduced auto return type deduction for functions, and given the allowed grammar for function definitions, as per C++14 the grammar allows explicitly-deleting a function with auto return type. Whether this corner case is useful or not is not really for the language ponder about, as there is always a cost of introducing corner cases (e.g. "the grammar for definitions of functions shall have a special case for auto type deduction"). Whilst there are limitations on where one may provide explicitly-defaulted function definitions ([dcl.fct.def.default]), the same restrictions do not apply for explicitly-deleted function definitions ([dcl.fct.def.delete]). which one of them is right here? A a = b; // error in Clang Clang is arguable wrong to pick the user-defined conversion function for this initialization. As per [dcl.init.general]/15.6, /15.6.2: Otherwise, if the initialization is direct-initialization, or if it is copy-initialization where the cv-unqualified version of the source type is the same class as, or a derived class of, the class of the destination, constructors are considered. [...] takes precedence over /15.6.3: Otherwise (i.e., for the remaining copy-initialization cases), user-defined conversions that can convert from the source type to the destination type or (when a conversion function is used) to a derived class thereof are enumerated as described in [over.match.copy], and the best one is chosen through overload resolution ([over.match]). [...] As a user of the language, providing a deleted definition of a function with auto return type could be used to semantically mark that no one should provide any kind of overload of a given function name. auto f() = delete; // never expose a valid overload for f() // elsewhere: int f() { return 42; } // error: functions that differ only in // their return type cannot be overloaded For the special case of user-defined conversion operators, an explicitly-default auto return type user-defined conversion function can be used e.g. in a intended-for-composition base class, similar to Scott Meyers C++03 trick of making a class non-copyable (before C++11 introduced = delete). struct NoUserDefinedConversionFunctionsAllowed { operator auto() = delete; }; struct S : NoUserDefinedConversionFunctionsAllowed { operator int() { return 1; } // can never be used };
69,194,439
69,194,666
Why does this merge sort code keeps giving me this weird output?
I wrote the count sort code but it is showing me weird output, can you tell where I am wrong ?? #include <bits/stdc++.h> using namespace std; void CountSort(int a[], int n, int k) { int count[k + 1]={0}; int b[n]; for (int i = 0; i < n; i++) { ++count[a[i]]; } for (int i = 1; i <= k; i++) { count[i] += count[i - 1]; } for (int i = 0; i >= 0; i--) { b[count[a[i]]-1] = a[i]; --count[a[i]]; } for (int i = 0; i < n; i++) { a[i] = b[i]; } } int main() { int a[] = {2, 1, 1, 0, 2, 5, 4, 0, 2, 8, 7, 7, 9, 2, 0, 1, 9}; CountSort(a, 17, 9); cout<<"The sorted array is -> "<<a; return 0; } It gives output like this - The sorted array is -> 0x7bfdd0 ScreenShot of the code and the output
Your code have two fault. print array method is wrong. third loop is wrong in CountSort. this loop working only once. There is fix result. void CountSort(int a[], int n, int k) { int count[k + 1]={0}; int b[n]; for (int i = 0; i < n; i++) { ++count[a[i]]; } for (int i = 1; i <= k; i++) { count[i] += count[i - 1]; } for (int i = 0; i < n; i++) { b[count[a[i]]-1] = a[i]; --count[a[i]]; } for (int i = 0; i < n; i++) { a[i] = b[i]; } } int main() { int a[] = {2, 1, 1, 0, 2, 5, 4, 0, 2, 8, 7, 7, 9, 2, 0, 1, 9}; CountSort(a, 17, 9); cout<<"The sorted array is -> "; for (int i = 0; i < 17; ++i) { cout << a[i] << ' '; } cout << endl; return 0; } result: The sorted array is -> 0 0 0 1 1 1 2 2 2 2 4 5 7 7 8 9 9
69,194,553
69,194,598
Differences between compare and == for std::string
I am getting different results when using == or std::string::compare between two strings. This is the code I am executing. #include <iostream> #include <string> int main() { std::string str1 = "W"; char tmpChar = 'W'; std::string str2(1, tmpChar); bool equalCompare = str1.compare(str2); bool equalSign = (str1 == str2); std::cout << "Compare result: " << equalCompare << std::endl; std::cout << "Equal sign result: " << equalSign << std::endl; return 0; } I guess it has to do with how I am creating str2, but that is the way I found out to convert a single char to a string.
Differences between compare and == for std::string The difference is in what they return. == returns true when the strings compare equal and false otherwise. compare returns negative integer when *this is before the argument, zero when strings are equal, and positive integer when the argument is before *this.
69,194,685
69,195,109
c++ program crashing after reading a file the second time
Basically, the problem is already described in the title: When starting the program first time ( meaning that the new file is created then ), it works perfectly and it doesn't crash, but when trying a second time ( meaning that the file already is there ), it crashes. Question is: Why does it crash and how do I prevent that from happening? Here's the code: #include <iostream> #include <fstream> #include <algorithm> #include <vector> using namespace std; class TStudent { public: string Name, Surname; int Age; TStudent(string name, string surname, int age) { Name = name; Surname = surname; Age = age; cout <<"\n"; } string toString() const { return Name + " ; " + Surname + " ; " + to_string(Age); } int aux1 = sizeof(Name), aux2 = sizeof(Surname); }; class TRegistru { public: string name, surname; int age; vector <TStudent> students; TRegistru(const TStudent &other) { this->name = other.Name; this->surname = other.Surname; this->age = other.Age; students.push_back(other); } void adauga(const TStudent& student) { students.push_back(student); } void salveaza(string file_name)// creating the file and storing the data { ofstream file1; file1.open(file_name, ios::app); file1.write((char*)&students, sizeof(students)); file1.close(); cout<<"\nFile saved and closed successfully.\n"<<endl; } void sterge() { students.clear(); } void incarca(string file_name)// opening the file and reading the data { ifstream file2; file2.open(file_name, ios::in); if(!file2) { cout<<"Error in opening file.."; } else { cout<<"File opened successfully.\n"<<endl; } file2.seekg(0); file2.read((char*)&students, sizeof(students)); } void afiseaza()//printing the data { for(auto student : students) { cout << student.Name << endl ; cout << student.Surname << endl; cout << student.Age << endl; cout <<"\n"; } } string toString() const { string ret{}; for(const auto& student : students) { ret += student.toString() + "\n"; } return ret; } }; int main() { TStudent student1("Simion", "Neculae", 21); TStudent student2("Elena", "Oprea", 21); TRegistru registru(student1); registru.adauga(student2); registru.salveaza("data.bin");// creating the file and storing the data registru.sterge(); registru.incarca("data.bin");// opening the file and reading the data registru.afiseaza();//printing the data return 0; }
After reading a second time your code I realised that the way you try to read and write a vector was plain wrong: vector <TStudent> students; ... ifstream file2; file2.open(file_name, ios::in); file2.seekg(0); file2.read((char*)&students, sizeof(students)); // WRONG!!! A vector does store its data in a contiguous way, but the address of the vector is not the address of the data. The correct way is to serialize each element of the vector to the file and then deserialize each element and push that into the vector.
69,194,690
69,195,699
Compare named requirement expressed with C++20 concepts
I am writing a sorting algorithm, that takes a comparison function, similar to std::sort: template <class RandomIt, class Compare> void sort(RandomIt first, RandomIt last, Compare comp); It seems to me that the template parameter Compare perfectly matches the Compare named requirement. I am trying to understand how to specify that constraint using C++ 20 concepts, such as std::strict_weak_order and std::equivalence_relation, but I am slightly confused. If I quote the article on cppreference, The type T satisfies Compare if The type T satisfies BinaryPredicate, and Given comp, an object of type T equiv(a, b), an expression equivalent to !comp(a, b) && !comp(b, a) std::strict_weak_ordering could capture my constraints on comp in the description above, but what about equiv? std::equivalence_relation takes a relation as a first template parameter. What would it be in my sorting function?
In C++, named requirements are wider in capabilities than concepts and constraints. For example, I can have a named requirement that some algorithms halts. On the other hand, there is no way to make a concept that requires an algorithm halts. Concepts can check some things, but they cannot check everything. So the named requirement Compare says first that the thing must be a BinaryPredicate. BinaryPredicate can be described as a concept and provided as a constraint. Confirming if comp(a,b)==true then comp(b,a)==false would require either a proof subsystem of C++ to be added and the formal proof to be passed in alongside comp, or checking every single value of the types you pass to comp. There are languages where you can pass around formal proofs of properties, and those formal proofs are checked to validate function arguments. C++ is not one of them. Rice's theorem states that you cannot take code and verify its non-trivial properties. To pull off something similar to what you want, code would have to be augmented with proofs of what you claim about it. This extra information could then be required by constraints. Using the Turing tar pit, you could even augment C++ with this capability, but it wouldn't look much like C++ afterwards (and that is coming from me, who likes to add named operators to C++ for fun). TL;DR not all named requirements can be expressed as concepts. Concepts can check some things, but not everything. Documenting additional requirements beyond what concepts constrain parameters is a thing in C++.
69,194,777
69,195,146
C++ Swapping pointers - can't reproduce auto type by defining type explicity
Doing exercise 6.22 in C++ Primer, a function swapping two pointers: void swap(int*& a, int*& b) { auto temp = a; a = b; b = temp; } int main() { int a = 15; int b = 4; int* p1 = &a; int* p2 = &b; cout << "p1 address: " << p1 << "; p1 value: " << *p1 << "\np2 address: " << p2 << "; p2 value: " << *p2 << endl; swap(p1, p2); cout << "p1 address: " << p1 << "; p1 value: " << *p1 << "\np2 address: " << p2 << "; p2 value: " << *p2 << endl; } Not sure if it's correct, but it works as expected, the values and addresses are swapped. I hover in MS Visual Studio over the a inside swap function: It tells me the type is int*&, but changing the definition of temp to int*& temp = a breaks the program: p1 address: 004FFE00; p1 value: 15 p2 address: 004FFDF4; p2 value: 4 p1 address: 004FFDF4; p1 value: 4 p2 address: 004FFDF4; p2 value: 4 What is the correct type here? What's the logic behind MS Visual Studio type tooltip?
As mentioned in the comments, temp is of type int*, not int*&. If you want it to be a reference to a pointer, you can declare the type explicitly or use auto&. However, what you really want is int* anyway. Think about how you would write this if you were swapping two ints instead: void swap(int& a, int& b) { int temp = a; a = b; b = temp; } Here, you want temp just to be an int because you just want it to store the value of a so you can copy it to b. There is no need for it to be a reference. As to your other question, what is happening when temp is a reference? a = 15 b = 4 Call swap() temp references a a references b (so temp references b) b references temp (so b references b) Both a and b now reference the value 4 To see this in action, walk through the function in debug mode and examine the pointer addresses and values at each step.
69,195,122
69,195,443
Qt Application exits with 0 when QMainWindow is minimized
This Qt project https://github.com/AmonRaNet/QGeoView exits when the main window is minimized ??!!?? Can someone give me an explanation please, I never saw that in my life with Qt. I'm using Windows 10 and I'm using the last version of Visual Studio 2019 C++ compiler. I have also used different Qt versions (the last version of Qt5 and the version provided by vcpkg). I have already read the mainwindow code and there's nothing wrong.
From mainwindow.cpp: void MainWindow::hideEvent(QHideEvent* /*event*/) { QApplication::quit(); }
69,195,269
69,196,719
Template metaprogramming recursive evaluation
template<typename T> struct rm_const_volatile { using type = T; }; // Call this (partial)specialization as "1" template<typename T> struct rm_const_volatile<const T> { // remove topmost const and recurse on T using type = typename rm_const_volatile<T>::type; }; // Call this (partial)specialization as "2" template<typename T> struct rm_const_volatile<volatile T> { // remove topmost volatile and recurse on T using type = typename rm_const_volatile<T>::type; }; I had defined the remove const volatile qualifier template meta-program as above. Logically, when I write rm_const_volatile<const volatile int>, my expectation is that compiler will evaluate in the following order: Case 1: rm_const_volatile<const volatile int> [Use specialization 1]-> rm_const_volatile<volatile int> [Use specialization 2]-> rm_const_volatile<int> [Use general template]-> int (final result). Case 2: rm_const_volatile<volatile const int> [Use specialization 2]-> rm_const_volatile<const int> [Use specialization 1]-> rm_const_volatile<int> [Use general template]-> int (final result). So in my view above template specialization and general definition suffices to remove any const volatile qualifiers. Cut the actual behavior errors out as ambiguous template instantiation. // In main() below two calls are present (refer cpp.sh link below mentioned for full code) ---- std::cout << "Is volatile const int integral type with rm_const_volatile: " << is_integral<rm_const_volatile<volatile const int>::type>::value << std::endl; std::cout << "Is const volatile int integral type with rm_const_volatile: " << is_integral<rm_const_volatile<const volatile int>::type>::value << std::endl; ------- In function 'int main()': 54:132: error: ambiguous class template instantiation for 'struct rm_const_volatile<const volatile int>' 26:8: error: candidates are: struct rm_const_volatile<const T> 31:8: error: struct rm_const_volatile<volatile T> 54:95: error: incomplete type 'rm_const_volatile<const volatile int>' used in nested name specifier 54:95: error: incomplete type 'rm_const_volatile<const volatile int>' used in nested name specifier 54:138: error: template argument 1 is invalid When I add following template specialization, everything works fine. template<typename T> struct rm_const_volatile<const volatile T> { using type = T; }; Please refer to this link for the full code. I would like to know why the compiler reports template instantiation as ambiguous, when clearly it can chop off the top most qualifier and recursively instantiate to the final result as I have mentioned in the case 1 & 2 above. Highly appreciate your valuable inputs and my sincere thanks for your time.
I would like to know why the compiler reports template instantiation as ambiguous C++ considers const volatile int and volatile const int to be the same type. They are interchangable and mean the same thing. Some other ways to spell this one type: int const volatile int volatile const const int volatile volatile int const That said, C++ will never change overload rules based on the way you choose to spell a particular type. Therefore, the template specializations <const T> and <volatile T> are both equally specialized for <const volatile int>. Neither qualifier takes priority over the other.
69,195,593
69,228,948
Would compiler optimization remove try/catch block if catch does nothing?
I am working with code that has a lot of try catch blocks in but most cases the catch blocks do nothing. As in the code below fib function is throwing invalid_argument exception. The function call in main is in the try block but the catch block does not do anything, except catching the exception. I am wondering if the compiler might trim away this kind of exception handling during code optimization, or not? #include <iostream> #include <exception> // Declaration for Wmissing-declarations flag int fib(int); int fib(int n) { if (n < 0) { throw std::invalid_argument("Invalid argument"); } if (n == 0 || n == 1) return n; return fib(n-1) + fib(n-2); } int main(int argc, char *argv[]) { int _number; std::cin >> _number; try { std::cout << fib(_number) << std::endl; } catch(const std::invalid_argument & e) { } return 0; } Compiling above code with most (all I know) flags turned on, as below, does not show any warning. g++ -o except exceptions.cxx -pedantic -Wall -Wextra -Wcast-align -Wcast-qual -Wctor-dtor-privacy -Wdisabled-optimization -Wformat=2 -Winit-self -Wlogical-op -Wmissing-declarations -Wmissing-include-dirs -Wnoexcept -Wold-style-cast -Woverloaded-virtual -Wredundant-decls -Wshadow -Wsign-conversion -Wsign-promo -Wstrict-null-sentinel -Wstrict-overflow=5 -Wswitch-default -Wundef -Werror -Wno-unused
I am wondering if the compiler might trim away this kind of exception handling during code optimization, or not? TL;DR: No, a compiler cannot and must not optimize away such exception handling. As mentioned in the comments, an empty catch block is not the same as not having try ... catch blocks. In your example, although there is no code actually executed in the catch block, the exception thrown when a negative number is passed to the fib function is still caught by that block. At that point, the catch block is conceptually entered, then exited pretty swiftly – passing control (silently) to the code immediately following that empty block. There will also be some (necessary) stack unwinding, and possibly other 'remedial' actions, performed when that catch block is invoked; thus, even such an empty catch block will still actually catch the relevant exceptions (specified as its arguments). So, for your code (as-is), entering a test value of -3 will result in normal, successful program termination. On my Windows console (invoked from Visual Studio), I see this: -3 C:\SGGCode.exe (process 2888) exited with code 0. Press any key to close this window . . . However, if I remove the try..catch block, giving the following main (leaving everything else untouched): int main(int argc, char* argv[]) { int _number; std::cin >> _number; std::cout << fib(_number) << std::endl; // Removed try...catch return 0; } Then, when I run the program and give the same input, I get this uncaught exception error: -3 C:\SGGCode.exe (process 2420) exited with code -1073740791. Press any key to close this window . . . (Note that -1073740791 is 0xc00004096, which is an uncaught exception error.) To make things a bit clearer, try adding a line like the following, immediately before the return 0; line in your main: std::cout << "See - I'm still here!" << std::endl; With your empty catch, that will execute; without it, the program will crash before it can get there.
69,195,929
69,200,969
What will happens to a local pointer if thread is terminated?
what happens to data created in local scope of thread if thread is terminated, memory leak? void MyThread() { auto* ptr = new int[10]; while (true) { // stuff } // thread is interrupted before this delete delete[] ptr; }
Okay, my perspective. If the program exits, the threads exit wherever they are. They don't clean up. But in this case you don't care. You might care if it's an open file and you want it flushed. However, I prefer a way to tell my threads to exit cleanly. This isn't perfect, but instead of while (true) you can do while (iSHouldRun) and set the field to false when it's time for the thread to exit. You can also set a flag that says, iAmExiting at the end, then myThread.join() once the flag is set. That gives your exit code a chance to clean up nicely. Coding this from the beginning helps when you write your unit tests. The other thing -- as someone mentioned in comments -- use RAII. Pretty much if you're using raw pointers, you're doing something you shouldn't do in modern C++. That's not an absolute. You can write your own RAII classes. For instance: class MyIntArray { MyArray(int sizeIn) { ... } ~MyArray() { delete array; } private: int * array = nullptr; int size = 0; }; You'll need a few more methods to actually get to the data, like an operator[]. Now, this isn't any different than using std::vector, so it's only an example of how to implement RAII for your custom data, for instance. But your functions should NEVER call new like this. It's old-school. If your method pukes somehow, you have a memory leak. If it pukes on exit(), no one cares. But if it pukes for another reason, it's a problem. RAII is a much, much better solution than the other patterns.
69,195,933
69,196,640
error: passing 'const S' as 'this' argument discards qualifiers
Here is an simplified version of the problem from ported from large code base. I've solved the issue, but I don't like the way I solved it. The problematic code that doesn't compile is this I'm starting with: #include <iostream> #include <cstdlib> #include <vector> #include <cassert> #include <algorithm> #include <cmath> #include <array> #include <utility> #include <set> #include <functional> class S { public: int a; int b; mutable int c; void set_c() { c = 222; } }; struct cmp { bool operator()(const S& lhs, const S& rhs) const { return !(lhs.a == rhs.a && lhs.b == rhs.b); } }; class core { public: std::set<S, cmp> set_of_S; std::function<void()> f; void set_fn() { f = [this]() { auto it = set_of_S.begin(); it->set_c(); }; } }; int main() { core core; S a {.a = 2, .b = 3, .c = 0}; S b {.a = 2, .b = 3, .c = 0}; S c {.a = 2, .b = 4, .c = 0}; core.set_of_S.insert(a); core.set_of_S.insert(b); core.set_of_S.insert(c); core.set_fn(); core.f(); std::cout << core.set_of_S.size() << '\n'; } The compiler error is: prog.cc: In lambda function: prog.cc:37:23: error: passing 'const S' as 'this' argument discards qualifiers [-fpermissive] it->set_c(); Ok, makes sense. As some people have told me, you should use the keyword mutable as this is not captured as a const and iterator it should be modifiable now (or atleast what I'm expecting): void set_fn() { f = [this]() mutable { auto it = set_of_S.begin(); it->set_c(); }; } This doesn't compile. This part doesn't make sense to me. So a member function cannot modify captured this inside lambda, but if you try to directly modify S::c inside the lambda compiler thinks that is okay. What? Doesn't make sense to me. When I change: void set_c() { c = 222; } to void set_c() const { c = 222; } It will finally compile, but I don't like the solution, because we had to modify the original function signature just because the lambda won't accept it and it makes it less readable. I see lambdas as a tool and not something you have to design against. I have tried placing mutable keyword all over the place, but can't get it to compile. And I think there should be a way to permit member function to modify it's own state inside lambda. Am I missing something or is this a compiler bug? Here is the problematic code in wandbox: https://wandbox.org/permlink/qzFMW6WIRiKyY3Dj I know this has been asked in: error: passing xxx as 'this' argument of xxx discards qualifiers but answers won't discuss on using mutable which to my understanding should solve these kind of situations.
Elements of a std::set<T> are unmodifiable - set_of_S.begin() returns a constant iterator: cppreference Because both iterator and const_iterator are constant iterators (and may in fact be the same type), it is not possible to mutate the elements of the container through an iterator returned by any of these member functions [begin/cbegin]. That means that the element pointed to by the iterator it is const, so you can't call a non-const function such as set_c on it. it->c = 300 still works because you've made c mutable. It has nothing to do with the lambda you're calling this in being mutable or not.
69,196,221
69,199,146
"This library now requires a C++11 or later compiler..." when compiling 'number_base.hpp' of boost library
I have a c++ project using boost 1.77.0 library. The compiler is g++ 4.8.5, and as I know it supports the c++11 standard. The following command is used to compile the project: g++ -std=c++11 main.cpp Logger.cpp MOCMesh.cpp Mesh.cpp CFDMesh.cpp Solver.cpp -o main -I../tools -I/usr/code/include -I. -L/usr/code/lib -lgmp -lphtread -lmpfr However, I got errors told c++ standard unsatisfied: /usr/code/include/boost/multiprecision/detail/number_base.hpp:36:2: error: #error "This library now requires a C++11 or later compiler - this message was generated as a result of BOOST_NO_CXX11_HDR_TYPE_TRAITS being set" #error "This library now requires a C++11 or later compiler - this message was generated as a result of BOOST_NO_CXX11_HDR_TYPE_TRAITS being set" ... For some reasons, I cannot update the GNU compilers to latest or higher version, so is there anyone knows how to solve this issue?
Use an older version of boost from that time period
69,196,433
69,196,868
C++ program for Gauss Jordan elimination returning a very small value but not 0
I made a program to solve linear equations using Gauss Jordan elimination method. The program is working correctly but in some cases instead of giving the answer as 0, it returns a very small value. #include<iostream> #include<iomanip> #include<cassert> #define N 10 using namespace std; //printing out the array void print(float x[][N], int n){ for(int i=0;i<n;i++){ for(int j=0;j<=n;j++) cout << setprecision(5) << setw(15) <<x[i][j]; cout << endl; } cout << endl; } //to normalise the leading entries to 1 void normalize(float x[][N], int n, int i, int j){ float fac = x[i][j]; for(int k=0;k<=n;k++) x[i][k] /= fac; } //check if the leading entry is a zero bool chk_zero(float x[][N], int n, int i){ int j, k, c{0}; if(x[i][i]==0){ for(j=i;j<n-1;j++){ c=1; while(x[j+c][i]==0 && i+c<n){ c++; if(i+c==n-1) assert(i+c==n-1 && "Equation has no solution"); return false; } for(k=0;k<=n;k++){ swap(x[i][k], x[i+c][k]); } return true; } } return true; } //Gauss Jordan elimination method void GaussJordan(float x[][N], int n){ int i, j, k, c; float rat; for(i=0;i<n;i++){ //not taking the zero in pivot column case chk_zero(x, n, i); normalize(x, n, i, i); for(j=0;j<n;j++){ if (i != j){ float fac{x[j][i]}; for(k=0;k<=n;k++) x[j][k] = x[j][k]-fac*x[i][k]; } } } } int main(){ float arr[][N] = { {0, 5, 1, 2}, {2, 11, 5, 3}, {1, 0, 0, 0} }; int n = sizeof(arr)/sizeof(arr[0]); print(arr, n); GaussJordan(arr, n); cout << n << endl; print(arr, n); return 0; } the output I get is: 1 0 0 2.3842e-08 0 1 0 0.5 -0 -0 1 -0.5 The output I should get is: 1 0 0 0 0 1 0 0.5 -0 -0 1 -0.5 The value 2.3842e-08 should be a zero. Is it because of the precision of the floating point in C++ ? If so, what should I do in order to round such low values to 0 without loss of data ? Also, why is there a "-0" instead of a 0.
The value 2.3842e-08 should be a zero. Is it because of the precision of the floating point in C++ ? Yes, it is. If so, what should I do in order to round such low values to 0 without loss of data ? You can use an epsilon value to decide whether a float value is considered to be 0: const float epsilon = 0.000001; // Depends on the use case of your application if (std::abs(some_float) < epsilon) { // Treat some_float as 0 } However, this approach has some cons. Read here for more. Also, why is there a "-0" instead of a 0. This is because of how float numbers are represented. Most C++ compilers use the IEEE 754 standard to implement floating point arithmetics. Few things to add (unrelated to the question): You should avoid using using namespace std as it pollutes the global namespace. Especially for large codebases. Use std::array<> instead of raw arrays as they are more safe.
69,196,563
69,196,777
How to find largest and smallest value from a file using loop
I am running into this issue where I want the largest and smallest value of id from a file that I am reading. This file contains other information as well. I am successfully able to identify the largest value but the smallest is just being set to the last value that gets read, which is not the smallest in the file. Here is the code largestId = 0; smallestId = 99999; while(theFile >> firstName >> lastName >> id) { if(id > largestId){ largestId = id; }else if(id < smallestId){ smallestId = id; } }
You don't check for error states. What about the situation were there are no values in the file. Or only one value in the file. You make assumptions about the size of largest and smallest values by using magic numbers. if (theFile >> firstName >> lastName >> id) { // You have at least one value it is the largest and smallest value. smallestId = largestId = id; while(theFile >> firstName >> lastName >> id) { // There is an argument that this would be better to write // as a function call as that would be self documenting. // id = std::max(id, largestId); if(id > largestId){ largestId = id; } if(id < smallestId){ smallestId = id; } } } else { // ERROR }
69,196,888
69,197,911
Accessing the same folder from different cpp files relative to the Project folder
If my project has the following folder structure: Project ├───build ├───images ├───include ├───Apps ├───Models ├───source └───tests what is the best way to make the folder "images" accessable to all .cpp files inside build, tests, apps and src without using the absolute path. So every image created inside this project should be saved to the "images" folder. I am building with Cmake if this is important(started using CMake last week so no deep knowledge). Main CmakeLists.txt file is the the root folder. Tests, Apps and source each have their own CMakeLists.txt files and executables. Every image will be created with the same class so I think I could use std::filesystem::current_path() with a wrapper function inside the class which would generate and set the desired path but there should be another way. I will also load files from the folder Models in the future, so the same problem.
If I am understanding your question correctly you want to access the images from the "images" folder, right? You should be thinking about the path from the point of the final executable and not the source files. If the executable will be in the build directory then you simply need to write "../images", the 2 dots mean that you are going back 1 directory.
69,197,072
69,197,231
WINAPI GetRawInputData gives an error because of wrong parameters
GetRawInputData() returns -1 (error) and GetLastError() returns 87 which is "The parameter is incorrect.", the first call to the function to get the data size succeeds but the second one, where I try to actually get the data, fails. UINT DataSize; if (GetRawInputData((HRAWINPUT)Message.lParam, RID_INPUT, NULL, &DataSize, sizeof(RAWINPUTHEADER)) == -1) { Error("Failed getting raw input amaount\n"); } RAWINPUT *Raw; Raw = (PRAWINPUT)VirtualAlloc(NULL, DataSize, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); if (!Raw) { Error("Failed to allocate memory!\n"); } if (GetRawInputData((HRAWINPUT)Message.lParam, RID_INPUT, Raw, &DataSize, sizeof(RAWINPUTHEADER) == -1)) // <-- Fails here { Error("Failed getting raw input\n"); }
As @dialer mentioned in a comment, the closing parenthesis are wrong in your 2nd call to GetRawInputData(): if (GetRawInputData(..., sizeof(RAWINPUTHEADER) == -1)) You are comparing the result of sizeof() to -1, and then passing the result of that comparison (0 or 1) to the cbSizeHeader parameter (and then checking whether GetRawInputData() returns a non-zero return value), hence the "invalid parameter" error. Which BTW, GetRawInputDaata() is NOT documented as using GetLastError() for error reporting, so you can't rely on that error code anyway when GetRawInputDaata() returns -1. Change your if statement to close like this instead: if (GetRawInputData(..., sizeof(RAWINPUTHEADER)) == -1)
69,197,173
69,197,289
confused about max size of std::vector
I ran into an issue in my code with std::vector, giving me: vector<T> too long. I'm using a vector of char in this case. The code is treating 3D (tomography) images, so I have a lot of voxels. I have exactly the same issue on windows using the VS compiler as on Mac using CLANG, not tested gcc yet. To inspect the issue, I added the following lines: printf("max vector size %u\n", v.max_size() ); printf("PTRDIFF_MAX %u, INTMAX_MAX %u\n", PTRDIFF_MAX, INTMAX_MAX ); Which gave me: max vector size 4294967295 PTRDIFF_MAX 4294967295, INTMAX_MAX 4294967295 I have two questions about this: Why is the max value so small? it looks like the max of an uint32. I was expecting it to be more in the range of size_t, which should be 18446744073709551615, right? Why am I getting the vector<T> too long when my vector surpasses 2147483648 (i.e. half the stated maximum) number of values? [edit] Some responses: Thank you for pointing out my printf mistakes. I've converted to std::cout and now I get (which makes more sense on a 64bit system): max_size: 9223372036854775807 PTRDIFF_MAX: 9223372036854775807 INTMAX_MAX: 9223372036854775807 The error vector<T> too long is a runtime error I traced it back to the line where I resize the vector When I use a vector of uint32_t instead of char, the problem arrises at the same vector length (at 4 times the memory usage). I have more than sufficient RAM, however, I don't know how allocation works upon a resize request. Perhaps, there isn't a sufficiently large continuous block of RAM available?
Why is the max value so small? it looks like the max of an uint32. That is to be expected on 32 bit systems. I was expecting it to be more in the range of size_t, which should be 18446744073709551615, right? If PTRDIFF_MAX is 4294967295, then I find it surprising that SIZE_MAX would be as much as 18446744073709551615. That said, I also would find it surpising that PTRDIFF_MAX was 4294967295. You're seeing surprising and meaningless output because the behaviour of the program is undefined which is because you used the wrong format specifier. %u is for unsigned int and only for unsigned int. %td specifier is for std::ptrdiff_t, PRIdMAX macro expands to the specifier for std::intmax_t and %zu is for std::size_t. I recommend learning to use the C++ iostreams. It isn't quite as easy to accidentally cause undefined behaviour using them as it is when using the C standard I/O. Why am I getting the vector too long when my vector surpasses 2147483648 (i.e. half the stated maximum) number of values? I don't know what getting "vector too long" means, but it's typical that you don't have the entire address space available to your program. It's quite possible that half of it is reserved to the kernel. max_size doesn't necessarily take such system limitations into consideration and is a theoretical limit that is typically not achievable in practice.
69,197,246
69,199,709
Initializing smart pointers in a tuple without knowing the type
I have a tuple of smart pointers (as a member of a class template) that I need to initialize. I use std::apply to iterate over tuples elsewhere, but how do I initialize them with new objects without knowing their type? Running the code below with a debugger tells me the elements in the tuple are still "empty" afterwards. What am I doing wrong here? struct A { int a = 1; } struct B { int b = 2; } std::tuple< std::unique_ptr< A >, std::unique_ptr< B > > my_tuple; std::apply( [] ( auto&... ptr ) { //std::unique_ptr< T > (..., ptr.reset( { } )); //ptr.reset( new T() ) }, my_tuple );
As noted in the comments, you can apply decltype to ptr to get the type of the unique_ptr, then apply element_type to it: std::apply([](auto &... ptr) { ((ptr = std::make_unique<typename std::remove_reference_t<decltype(ptr)>::element_type>()), ...); }, my_tuple ); (I've replaced new with make_unique, and moved ... to the end, but those are just style clanges.) This can be shortened with C++20 template lambdas: std::apply([]<typename ...P>(std::unique_ptr<P> &...ptrs ) { ((ptrs = std::make_unique<P>()), ...); }, my_tuple );
69,197,293
69,200,568
Is it really possible to separate storage allocation from object initialization?
From [basic.life/1]: The lifetime of an object or reference is a runtime property of the object or reference. A variable is said to have vacuous initialization if it is default-initialized and, if it is of class type or a (possibly multi-dimensional) array thereof, that class type has a trivial default constructor. The lifetime of an object of type T begins when: storage with the proper alignment and size for type T is obtained, and its initialization (if any) is complete (including vacuous initialization) ([dcl.init]), except that if the object is a union member or subobject thereof, its lifetime only begins if that union member is the initialized member in the union ([dcl.init.aggr], [class.base.init]), or as described in [class.union] and [class.copy.ctor], and except as described in [allocator.members]. From [dcl.init.general/1]: If no initializer is specified for an object, the object is default-initialized. From [basic.indet/1]: When storage for an object with automatic or dynamic storage duration is obtained, the object has an indeterminate value, and if no initialization is performed for the object, that object retains an indeterminate value until that value is replaced ([expr.ass]). [Note 1: Objects with static or thread storage duration are zero-initialized, see [basic.start.static]. — end note] Consider this C++ program: int main() { int i; i = 3; return 0; } Is initialization performed in the first statement int i; or second statement i = 3; of the function main according to the C++ standard? I think it is the former, which performs vacuous initialization to an indeterminate value and therefore begins the lifetime of the object (the latter does not perform initialization, it performs assignment to the value 3). If that is so, is it really possible to separate storage allocation from object initialization?
If that is so, is it really possible to separate storage allocation from object initialization? Yes: void *ptr = malloc(sizeof(int)); ptr points to allocated storage, but no objects live in that storage (C++20 says that some objects may be there, but nevermind that now). Objects won't exist unless we create some there: new(ptr) int;
69,197,306
69,198,259
Sending a file via multipart using libcurl in C++
I am trying to upload a file via a POST request to a remote location using libcurl and C++. However, I think I am doing something wrong because I am told that the file doesn't arrive on the other side. I am using the following code: #include "curl/curl.h" using namespace std; size_t WriteCallback(void * buffer, size_t size, size_t count, void * user) { ((string *) user)->append((char *) buffer, 0, size * count); return size * count; } int main() { curl_global_init(CURL_GLOBAL_ALL); CURL * Curl; CURLCode res; Curl = curl_easy_init(); curl_easy_setopt(Curl, CURLOPT_FAILONERROR, 0); curl_easy_setopt(Curl, CURLOPT_VERBOSE, 1L); struct curl_httppost * formpost = NULL; struct curl_httppost * lastptr = NULL; struct curl_slist * headerlist = NULL; static const char buf[] = "Expect:"; ImageName = "myimage.jpg" ImageNameWithPath = "/this/location/right/here/" + ImageName; curl_formadd(& formpost, & lastptr, CURLFORM_COPYNAME, ImageName.c_str(); CURLFORM_FILE, ImageNameWithPath.c_str(); CURLFORM_CONTENTTYPE, "image/jpeg (binary)"; CURLFORM_END); curl_formadd(& formpost, & lastptr, CURLFORM_COPYNAME, ImageName.c_str(); CURLFORM_COPYCONTENTS, ImageNameWithPath.c_str(); CURLFORM_CONTENTTYPE, "image/jpeg (binary)"; CURLFORM_END); headerlist = curl_slist_append(headerlist, buf); string MessageBodyLine1 = "Content-Disposition: form-data; name=\"file\"; filename\"" + ImageName + "\""; headerlist = curl_slist_append(headerlist, MessageBodyLine1.c_str()); string Url = https://www.example.com/ // There is a real URL here curl_easy_setopt(Curl, CURLOPT_URL, Ulr.c_str()); curl_easy_setopt(Curl, CURLOPT_HTTPHEADER, headerlist); curl_easy_setopt(Curl, CURLOPT_HTTPPOST, formpost); string Reponse; curl_easy_setopt(Curl, CURLOPT_WRITEFUNCTION, WriteCallback); curl_easy_setopt(Curl, CURLOPT_WRITEDATA, & Response); res = curl_easy_perform(Curl); curl_easy_cleanup(Curl); curl_formfree(formpost); curl_slist_free_all(headerlist); curl_global_cleanup(); return 0; I actually expected the output to look something like this somewhere POST URL HTTP/1.1 Content-Type: multipart/form-data; boundary=----BoundaryString ----BoundaryString Content-Disposition: form-data; name="file"; filename="myfile.jpg" Content-Type: image/jpeg (binary) and instead I get this: * Trying IP * Connected to IP port PORT (#0) POST URL HTTP/1.1 Host: IP Accept: IP:PORT Content-Disposition: form-data; name="file"; filename="myfile.jpg" Content-Length: totalsize Content-Type: multipart/form-data; boundary=----BoundaryString < HTTP/1.1 200 OK [...] Now it says OK but I know for a fact that the image does not arrive on the other side. Furthermore my Response string is also empty whereas it should contain a JSON string. What am I doing wrong? Unfortunately I am stuck with a older libcurl version and thus cannot use the mime format available in curl 7.55.
DO NOT add a Content-Disposition request header to the headerlist of the HTTP request, it does not belong there. It belongs inside each MIME part instead (ie, you should be using CURLFORM_COPYNAME, "file" and CURLFORM_FILE, ImageName.c_str()). I would expect curl_formadd() to handle the Content-Disposition for you, you should not need to create it manually. Also, image/jpeg (binary) is not a valid Content-Type value, it needs to be just image/jpeg. And why are you calling curl_formadd() twice for the same file, one with CURLFORM_FILE and the other with CURLFORM_COPYCONTENTS? Especially since your input to CURLFORM_COPYCONTENTS is wrong (it expects a pointer to actual data, not a pointer to a filename string). You should be using only CURLFORM_FILE in this situation. Try this: #include "curl/curl.h" #include <string> using namespace std; size_t WriteCallback(void * buffer, size_t size, size_t count, void * user) { size_t numBytes = size * count; static_cast<string*>(user)->append(static_cast<char*>(buffer), 0, numBytes); return numBytes; } int main() { curl_global_init(CURL_GLOBAL_ALL); CURL *Curl = curl_easy_init(); if (!Curl) return -1; curl_easy_setopt(Curl, CURLOPT_FAILONERROR, 0); curl_easy_setopt(Curl, CURLOPT_VERBOSE, 1L); curl_httppost *formpost = NULL; curl_httppost *lastptr = NULL; string ImageName = "myimage.jpg"; string ImageNameWithPath = "/this/location/right/here/" + ImageName; curl_formadd(&formpost, &lastptr, CURLFORM_COPYNAME, "file", CURLFORM_FILE, ImageNameWithPath.c_str(), CURLFORM_CONTENTTYPE, "image/jpeg", CURLFORM_END); curl_slist *headerlist = curl_slist_append(NULL, "Expect:"); string Url = https://www.example.com/ // There is a real URL here curl_easy_setopt(Curl, CURLOPT_URL, Url.c_str()); curl_easy_setopt(Curl, CURLOPT_HTTPHEADER, headerlist); curl_easy_setopt(Curl, CURLOPT_HTTPPOST, formpost); string Reponse; curl_easy_setopt(Curl, CURLOPT_WRITEFUNCTION, WriteCallback); curl_easy_setopt(Curl, CURLOPT_WRITEDATA, &Response); CURLCode res = curl_easy_perform(Curl); curl_easy_cleanup(Curl); curl_formfree(formpost); curl_slist_free_all(headerlist); curl_global_cleanup(); return 0; }
69,198,007
69,198,042
What are the options for safely modifying and reading a boolean across multiple threads and cpus?
I have some C++ code that contains roughly this logic: class wrapper_info { public: bool isConnected(); void connectedHandler(); void disconnectedHandler(); protected: bool _connected; } void wrapper_info::connectedHandler() { _connected = true; } void wrapper_info::disconnectedHandler() { _connected = false; } bool wrapper_info::isConnected() { return _connected; } extern "C" bool is_connected(void *obj) { wrapper_info *wrapper_obj = reinterpret_cast<wrapper_info*>(obj); return wrapper_obj->isConnected(); } For reasons mostly out of my control, different threads (running on different CPU cores) call these functions in the following way. Thread 1, 2, 3: is_connected(obj) Thread 2: connectedHandler() when the connection is initiated. Thread 3 disconnectedHandler() when the connection is broken. I am thinking there could be issues in the event of repeated calls to connectedHandler() and disconnectedHandler(), issues with the two threads writing to _connected and the writes getting out of order, resulting in the wrong final value. And potentially also issues with polling _connected as well. My questions are: What potential issues could actually arise from separate threads polling and modifying the value of _connected? What options are there to prevent these? Perhaps making _connected a volatile bool might solve issues polling the value. I was also thinking for the issue of threads 2 and 3 modifying its value, perhaps making it an atomic bool and using atomic set operations will be sufficient to prevent issues like out-of-order memory operations. I also know other potential solutions are locks or memory barriers like smb_mb. However, I am not sure what I should use. Thank you lots.
What potential issues could actually arise from separate threads polling and modifying the value of _connected? It's Undefined Behavior, no matter what. What options are there to prevent these? A common solution is to use std::atomic<bool> instead of bool. There are fancier (and much more complex) ways to ensure synchronization between threads, but std::atomic is an excellent first choice, and not difficult to use correctly. Perhaps making _connected a volatile bool might solve issues It won't. volatile does not solve thread synchronization issues.
69,198,166
69,199,810
How do I fill an array in c++ using a class?
This is a part of my assignment that I was given in my college CSCI course using C++ Create a class Array, representing an arran of size n, with the private properties: class Array {private: double * a {}; int n; Constructor by default Constructor by specifying the size of the array Constructor by specifying the size of the array, and the default value for all the elements in the array Constructor by copy Destructor Accessor: Retrieve the size of the array I was faced with the task of defining an array using a class and the class must contain what each bullet point says. However, I am stuck on bullet point number 3. I am attempting to fill the array with default values of 0 for a[0], 1 for a1, etc. depending on the size of the array that a user inputs and sets as value n. In doing so all that my code is doing is assigning each and every element in the array with a value of 0. #include <iostream> using namespace std; class MyArray { private: double * a {}; int n; public: MyArray(); explicit MyArray(int size); MyArray(int size, double def_val); MyArray(const MyArray & a2); ~MyArray(); int get_Size() const; void SetElement(int i, double x); double GetElement(int i); void display(); }; MyArray::MyArray(int size) { n = size; a = new double[size]; } MyArray::MyArray() { a = nullptr; n = 0; } double MyArray::GetElement(int i) { return a[i]; } void MyArray::SetElement(int i, double x) { a[i] = x; } MyArray::MyArray(const MyArray & a2) { n = a2.n; for (int i = 0; i < n; i++) { a[i] = a2.a[i]; } } //constructor by copy MyArray::~MyArray() { delete[] a; } MyArray::MyArray(int size, double def_val) { //THIS IS WHERE IT SHOULD ASSIGN n = size; a = new double[size]; for (int i = 0; i < size; ++i) { a[i] = i; } } int MyArray::get_Size() const { return n; } void MyArray::display() { cout << "The values of the array MyArray are: " << endl; for (int i = 0; i < n; i++) { cout << a[i] << " "; } cout << endl; } int main() { MyArray a(5); a.display(); return 0; } The output is this The values of the array MyArray are: 0 0 0 0 0
You are calling the wrong constructor you need to call this one: MyArray(int size, double def_val) not this: MyArray(int size); like this: int main(){ MyArray a(5,5); a.display(); } you will get the output as 0,1,2,3,4 But I don't think this is what the assignment wants you to do As you said it should "Constructor by specifying the size of the array, and the default value for all the elements in the array" so I think you should modify your constructor to be like this: MyArray::MyArray(int size, double def_val) { n = size; a = new double[size]; for (int i = 0; i < size; ++i) { a[i] = def_val; } }
69,198,680
69,198,951
How can I pass variables from Python back to C++?
I have 2 files - a .cpp file and a .py file. I use system("python something.py"); to run the .py file and it has to get some input. How do I pass the input back to the .cpp file? I don't use the Python.h library, I have two separate files.
system() is a very blunt hammer and doesn't support much in the way of interaction between the parent and the child process. If you want to pass information from the Python script back to the C++ parent process, I'd suggest having the python script print() to stdout the information you want to send back to C++, and have the C++ program parse the python script's stdout-output. system() won't let you do that, but you can use popen() instead, like this: #include <stdio.h> int main(int, char **) { FILE * fpIn = popen("python something.py", "r"); if (fpIn) { char buf[1024]; while(fgets(buf, sizeof(buf), fpIn)) { printf("The python script printed: [%s]\n", buf); // Code to parse out values from the text in (buf) could go here } pclose(fpIn); // note: be sure to call pclose(), *not* fclose() } else printf("Couldn't run python script!\n"); return 0; } If you want to get more elaborate than that, you'd probably need to embed a Python interpreter into your C++ program and then you'd be able to call the Python functions directly and get back their return values as Python objects, but that's a fairly major undertaking which I'm guessing you want to avoid.
69,198,682
69,198,758
Issue using FILE* with std::getline()
I would like to get some advice on an issue I've encountered once working on small adjustments to an existing program. The program itself has to: Open a file and read it line-by-line preferably Pack the lines into istringstream and then split to 2 strings on a ':' separator Insert those 2 strings line1 and line2 into an existing std::map container Than I can do more stuff with the map and the data from it. My code looks like that: int main() { FILE *fpFile; map<string, string>mapOfPci; std::string tempBuff=""; std::string line1="", line2=""; fpFile = fopen(PCI_MAPPING_PATH, "r"); if(!fpFile) return false; while(getline(fpFile, tempBuff)){ istringstream iSs(tempBuff); iSs >> line1; iSs.ignore(numeric_limits<std::streamsize>::max(), ':'); iSs >> line2; mapOfPci.insert(make_pair(line1, line2)); } for(const auto &m : mapOfPci){ cout << m.first << " : " << m.second << "\n"; } fclose(fpFile); return (0); } Now what I'm getting in my compiler feedback is: mismatched types 'std::basic_istream<_CharT, _Traits>' and 'FILE* {aka _iobuf*}' while(getline(fpFile, tempBuff)) At this point I presume that this is due to the usage of FILE* file handling method. I might not be able to use the C++ std::ifstream, std::fstream, so is there any method to move this further with the current FILE* usage?
std::getline() expects an std::istream-derived class, like std::ifstream, so you simply can't pass your own FILE* to it (unless you wrap it inside of a custom std::streambuf-derived object assigned to a standard std::istream object. std::ifstream uses std::filebuf, which uses FILE* internally, but you can't supply it with your own FILE*). Otherwise, you can use C's getline() function instead, but it doesn't work with std::string, as it allocates its own output char[] buffer which you will then have to free afterwards (you can assign the contents of that buffer to a std::string, though), eg: #include <iostream> #include <sstream> #include <string> #include <utility> #include <limits> #include <cstdio> using namespace std; int main() { FILE *fpFile = fopen(PCI_MAPPING_PATH, "r"); if (!fpFile) return false; map<string, string> mapOfPci; char *tempBuff = nullptr; size_t size = 0; int nRead; while ((nRead = getline(&tempBuff, &size, fpFile)) != -1){ istringstream iSs(string(tempBuff, nRead)); string line1, line2; iSs >> line1; iSs.ignore(numeric_limits<streamsize>::max(), ':'); iSs >> line2; mapOfPci.insert(make_pair(line1, line2)); free(tempBuff); tempBuff = nullptr; size = 0; } free(tempBuff); for(const auto &m : mapOfPci){ cout << m.first << " : " << m.second << "\n"; } fclose(fpFile); return 0; } But, since you are using other C++ standard classes, there really is no good reason not to use std::ifstream instead, eg: #include <iostream> #include <fstream> #include <sstream> #include <string> #include <utility> #include <limits> using namespace std; int main() { ifstream fpFile(PCI_MAPPING_PATH); if (!fpFile.is_open()) return false; map<string, string> mapOfPci; string tempBuff; while (getline(fpFile, tempBuff)){ istringstream iSs(tempBuff); string line1, line2; iSs >> line1; iSs.ignore(numeric_limits<streamsize>::max(), ':'); iSs >> line2; mapOfPci.insert(make_pair(line1, line2)); } for(const auto &m : mapOfPci){ cout << m.first << " : " << m.second << "\n"; } return 0; }
69,199,129
69,199,965
Casting derived template class from virtual class
In my code, I have one abstract class and ~8 child classes. I want to ask, is it possible in C++ to cast typename and return the calling class? I need something like separate A<int> as A and int. I need something like this: template <typename T> class Base { T data; virtual void setData(T p_data) = 0; virtual ~Base(); template<class TC<typename TV>> operator TC<TV>() const { TV tmp = (TV) data; return TC<TV>(tmp); } }; template <typename T> class A : public Base<T> { A(T data) { std::cout << data << std::endl; } void setData(T p_data) override { data = p_data; } }; I used to use D. In D, the next code solves this problem (I have included the D code below for a better understanding of what I want): auto opCast(K, this R)() const { static if (is(R ClassType : Root!T, alias Root)) K tmp = cast(K) data; return new Root!K(tmp); else throw new Exception("ClassType isn't equal (T)"); } Is there a solution for C++?
If I'm reading your D code correctly, you are basically: taking the ClassType of the this object that is being converted, pattern-matching it to make sure it is a template with 1 argument, and then extracting the type of that template, casting the this object's data member to a specified input type, returning a new object of the template with the specified type as its argument. There is nothing like ClassType in C++, so it is not possible for a base class to obtain the class type of a derived object, unless you use CRTP to pass the derived type as a template parameter to the base class. However, the operator you have is close to accepting any kind of template type for conversion, your syntax is just a little wrong. Try something more like this: template <typename T> class Base { public: T data; ... template<template<typename> typename TC, typename TV> operator TC<TV>() const { TV tmp = (TV) data; return TC<TV>(tmp); } }; Then something like this would work: A<int> d(7); A<float> e = d; std::cout << e.data << std::endl; Online Demo The catch is that this operator will convert to any template that takes an argument that data can be converted to. If you want to restrict the operator to only the same template that is being converted, you will need something more like this: template <typename T, template<typename> typename Derived> class Base { public: T data; ... template<typename TV> operator Derived<TV>() const { return Derived<TV>(data); } }; template <typename T> class A : public Base<T, A> { typedef Base<T, A> my_base; public: A(T p_data) { setData(p_data); std::cout << my_base::data << std::endl; } void setData(T p_data) override { my_base::data = p_data; } }; Online Demo
69,199,708
69,199,802
SetEnvironmentVariable() does not seem to set values that can be retrieved by getenv()
I have an EXE which, at startup, sets an environment variable (ie: MAGICK_CODER_MODULE_PATH=xxx) via the Windows API SetEnvironmentVariable(). When I look in Process Explorer (from SysInternals) at the list of environment variables set to my EXE I can see the environment variable I just set before (MAGICK_CODER_MODULE_PATH), so everything looks good at this point. Then I instruct my EXE to load a DLL via LoadLibrary(). The problem arises a little later when this DLL tries to get the value of my environment variable via getenv("MAGICK_CODER_MODULE_PATH"): it returns NULL! How could this be possible? It looks like getenv() ignores the value I just set before with SetEnvironmentVariable(). Note: This seems to not happen when the DLL is compiled with an old version of Visual Studio (maybe related to vcruntime140.dll / msvcp140.dll). If I open a command prompt, do @SET MAGICK_CODER_MODULE_PATH=xxx, and from this command prompt then launch my EXE, then everything works fine: the DLL successfully gets the value of MAGICK_CODER_MODULE_PATH via getenv().
You're mixing APIs: Windows' SetEnvironmentVariable bypasses the C++ runtime, so that the copy of the environment that is stored in your program is not updated. The later getenv call looks into this copy and doesn't find your change. Use the same API level for both calls. Either getenv and _putenv, or use the Windows API GetEnvironmentVariable and SetEnvironmentVariable.
69,200,251
69,200,274
arduino mqttclient callback which is a class method function
I'm using the following Arduino MQTT library (https://github.com/256dpi/arduino-mqtt) which apparently supports passing a callback which is a method of a class and not of a free function via: void onMessageAdvanced(MQTTClientCallbackAdvancedFunction cb); // Callback signature: std::function<void(MQTTClient *client, char topic[], char bytes[], int length)> however the following code doesn't compile: #include <ESP8266WiFi.h> #include <MQTT.h> class MyClass { public: void connect(); void loop(); void messageReceived(MQTTClient *client, char[], char[], int); WiFiClient net; MQTTClient client; unsigned long lastMillis = 0; }; void MyClass::connect() { Serial.print("checking wifi..."); while (WiFi.status() != WL_CONNECTED) { Serial.print("."); delay(1000); } Serial.print("\nconnecting..."); while (!client.connect("arduino", "public", "public")) { Serial.print("."); delay(1000); } Serial.println("\nconnected!"); client.subscribe("/hello"); // client.unsubscribe("/hello"); } void MyClass::messageReceived(MQTTClient *client, char topic[], char payload[], int length) { //Serial.println("incoming: " + topic + " - " + payload); } void MyClass::loop() { client.loop(); delay(10); // <- fixes some issues with WiFi stability if (!client.connected()) { connect(); } // publish a message roughly every second. if (millis() - lastMillis > 1000) { lastMillis = millis(); client.publish("/hello", "world"); } } MyClass ple; void setup() { Serial.begin(115200); WiFi.begin("essid", "passw"); ple = MyClass(); ple.client.begin("192.168.1.23", ple.net); ple.client.onMessageAdvanced(&ple.messageReceived); ple.connect(); } void loop() { ple.loop(); } it returns: cannot declare member function 'static void MyClass::messageReceived(MQTTClient*, char*, char*, int)' to have static linkage [-fpermissive] is there a way to pass a callback which is a method of a class?
A pointer to a member function is a fundamentally different type than a pointer to a free function. Adding static to the member function would work only if it doesn't access any instance data. If that's actually the case, you need to add static to the class body's declaration, and not the full definition of the function. If you need to access member data, you have a deeper issue. A C library wants pointers to functions, and one typically uses an extra parameter for "user data" or somesuch to hold the object address, and a helper function to transform the C callback into a member function call. If the library is written in C++, the callback can use std::function rather than a primitive function pointer, and then it can take a bound member function. // Callback signature: std::function<void(MQTTClient *client, char topic[], char bytes[], int length)> OK... so it is a std::function. You can't just pass the pointer to a member function by itself but need an instance to call it on as well. The normal way to do this is with a lambda expression: ple.client.onMessageAdvanced( [&ple] (MQTTClient *client, char topic[], char bytes[], int length) {ple.messageReceived(client,topic,bytes,length); } );
69,200,506
69,200,636
Identical code using more than double the RAM memory on different computers
I'm creating a Minecraft clone in C++ with OpenGL. I noticed today that when debugging the program on my laptop, the RAM usage is way higher that the RAM usage on my desktop PC (~1.3gb vs ~500mb). I'm getting these memory numbers from Visual Studio's diagnostics tools. I'm using GitHub and even with the same branch, same commit, literally the exact same code, the laptop uses more RAM. I tried cleaning the solution, rebuilding, cloning again, nothing works. The memory usage is different on the Windows Task Manager, too. I'm out of ideas of what could be happening. The computers are on different platforms (laptop is Intel 10th, and desktop is Ryzen 3000), the laptop has less RAM (8gb vs 16gb). Both are using the latest Windows 10. I'm using Visual Studio Community 2019. I'm not sure if a platform difference could cause such a huge impact on memory allocation.
Many laptop architectures use something called unified memory. That is to say, there is only one big pool of memory that is shared between the CPU and GPU (or the equivalent portions on an APU). On such architectures, allocating video memory is essentially the same thing as allocating RAM. It's all hidden away by the graphics drivers though. So a graphics-heavy application using more RAM on a laptop than on a desktop with a discrete GPU is not surprising. However, it's not so much that it uses more memory, just that the memory it uses gets tabulated differently. Assuming both platforms run at the same resolution and the same assets are loaded, you'd expect GPU Memory + RAM usage on desktop would be roughly equivalent to RAM usage on the laptop. Emphasis on the word roughly. Different graphic architectures/drivers use memory differently, so don't expect a 1-to-1 match here. For example: A single 1080p framebuffer takes a few megabytes at the minimum, depending on how the driver interacts with the actual screen, how many of these are around is rarely obvious. Tiled architectures can completely bypass needing large chunks of memory altogether. That's the most likely scenario here.
69,200,640
69,200,701
Class reference member - Not an error in a class with synthesized constructor but error in user defined constructor
Below errors out. Understood. class a { int b; int &c; // uninitialized a(int x): b(x) {} }; Below uses synthesized constructor. Why no error below? How does the synthesized constructor initialize the reference or will it even do that? Reference has to be user initialized from what I understand. class a { int b; int &c; };
The error in your first class comes here: a(int x): b(x) {} // error This is because you've defined a constructor that doesn't initialize the reference member c. This is an ill-formed constructor, and so the compiler gives an error. In the second class, the compiler will synthesize a constructor, so there's no error. However, that constructor is defined as deleted, and so you won't be able to create an object of this type. a test1{}; // error a test2{1, n}; // also error (assuming n is an int) demo So essentially, the error in the first case is that the class definition is ill-formed. In the second case, it's a well-formed class with a deleted constructor, which may be intentional.
69,200,663
69,200,843
Static method in base class reflect the derived class name
Here is base class: class Product { public: static void RegisterClass() { string b = __FUNCTION__; }; } and here is the derived class. class Milk: Product {} in the main function I call the static method this way: main(){ Milk.RegisterClass(); } Then it writes value Product::RegisterClass into variable b. Is there a way to get value Milk::RegisterClass in the static method. I don't want to instantiate the classes. And the main goal behind this scenario is to register Milk string somewhere.
The fairly constrained scenario presented by OP can be achieved reasonably well with the use of CRTP. As pointed out in the comments, type_info::name() is fraught with uncertainty, so a better approach would be to explicitly state the string to use: #include <string> #include <string_view> #include <iostream> template<typename CRTP> class Product { public: static void RegisterClass() { std::string b{CRTP::product_name}; std::cout << b << "\n"; }; }; class Milk : public Product<Milk> { public: static constexpr std::string_view product_name{"Milk"}; }; int main() { Milk::RegisterClass(); }
69,200,846
69,200,947
copy assignment operator implicitly deleted because field has a deleted copy assignment operator
I'm getting this error as soon as I define a destructor, but without that the compilation succeed, but I badly want to define destructor to debug some seg faults. class Socket { private: seastar::output_stream<char> socket; public: std::string peer; public: Socket() = default; template <typename... Args> explicit Socket(seastar::output_stream<char> &&s, std::string p) : socket(std::move(s)), peer(p) {} ~Socket() { std::cout << "Socket has gone out of scope" << "\n"; } seastar::future<> send(std::string message) { co_await socket.write(message); co_await socket.flush(); } seastar::future<> close() { co_await socket.close(); } }; Compilation fails with, error: object of type 'Socket' cannot be assigned because its copy assignment operator is implicitly deleted connection->second.socketObj = std::move(socketObj); ^ ./socketwrapper.h:44:46: note: copy assignment operator of 'Socket' is implicitly deleted because field 'socket' has a deleted copy assignment operator seastar::output_stream<char> socket; Is there anyway to fix this issue?
Add Socket(Socket&&)=default; Socket& operator=(Socket&&)=default;
69,201,102
69,201,162
In C++ is there an optimal way to run down a pointer chain to the value?
Lets say I have a program and a value like int finalValue = 1234;. Next there are pointers that point to finalValue. For Example: int *p = &finalValue; int **p2p = &p; int ***p2p2p = &p2p; If I wanted to create a function that ran down the pointer chain till it got to the finalValue (1234) what would be the most optimal way of doing it if the number of pointers too pointers can change. The function would be given the first pointer in the chain (so in the above case p2p2p). General traversal would look like p2p2p -> p2p -> p -> finalvalue. How do I do this for an unknown number of pointer in a chain (min 1, max of 5) Initial prototyping brought me to using foo(pointer) { while (typeid(pointer).name() != "int") { //do traversal through pointer chain } return pointer; //at this point it would have the value 1234 } But I dont know how to properly traverse down the chain, or how to efficiently check and stop. Any help is appreciated.
If you have c++17, you can use a recursive function like so: template<typename T> constexpr auto get_pointer_value(T v) { if constexpr (std::is_pointer_v<T>) { if (!v) { // Optional error handling if you can't trust the caller. throw std::invalid_argument("Pointer v cannot be null"); } return get_pointer_value(*v); } else { return v; } } Live example. The intent is nice and clear and this should all be sorted out at compile time. If you do trust the user, it might be worth adding an assert(v) to the pointer section of the constexpr if anyway.
69,201,244
69,233,940
Creating a makefile for a C++ Project
I'm currently trying to write a Makefile which searches the current directory and all sub-directories for C++ files, then compiles them one by one (if they haven't already been compiled or edited since the last time it was compiled) into an individual Object file at the location ./Objects, before finally using the Object files and linking them all into the final program. I've figured out how to find all the files using the "shell find" command. However, I'm stuck trying to figure out how to compile the source files into objects file one at a time. Here's my code: Appname := App #The Directory ObjectsDir := ./Objects #Find all the source files SrcFiles = $(shell find . -name "*.cpp") #Get their names only SrcFilesName = $(notdir $(SrcFiles)) #Add a .o suffix for the Object files name ObjectsSuffix = $(addsuffix .o, $(SrcFilesName)) #Add the prefix "Objects/" as I wish to output all the objects to ./Objects #A Source Files such as "./Test/Source/Test.cpp" becomes "./Objects/Test.cpp.o" Objects = $(addprefix ./Objects/, $(ObjectsSuffix)) #Compiler related Variables CXX = g++ CXXFLAGS = -Wall -std=c++20 -fsanitize=address CPPFLAGS = -DDEBUG -I ./Game/Headers -I ./Engine/Headers -I ./Engine/Headers/External LDLIBS = $(shell sdl2-config --libs) -l dl all : $(Appname) $(Appname) : $(Objects) $(CXX) $(CXXFLAGS) $(CPPFLAGS) $(Objects) -o $(Appname) $(LDLIBS) #The Problematic rule #I would like this to run once per source file if they haven't been compiled or changed/edited, so that I don't end up recompiling the entire code base $(ObjectsDir)/%.o: %.cpp mkdir -p Objects $(CXX) $(CXXFLAGS) $(CPPFLAGS) -MMD -MP -c $^ -o $@ $(LDLIBS) Note: The makefile currently works when all source files are in the base directory. However, when having a more complex layout, with multiple sub-directories errors such as make: *** No rule to make target 'Objects/Engine.cpp.o', needed by 'App'. Stop. occur.
For anyone in the future wondering how to setup a makefile, here's my final makefile. Appname := App #Output Dir for Object and dependency files ObjectsDir := ./Objects #Find all the source files SrcFiles := $(shell find . -name "*.cpp") #Create a variable holding all the objects Objects := $(patsubst %.cpp,$(ObjectsDir)/%.o,$(SrcFiles)) #Compiler Flags CXX = g++ CXXFLAGS = -Wall -std=c++20 -fsanitize=address CPPFLAGS = -DDEBUG -I ./Game/Headers -I ./Engine/Headers -I ./Engine/Headers/External LDLIBS = $(shell sdl2-config --libs) -l dl .PHONY: all all : $(Appname) #Link the object files $(Appname) : $(Objects) $(CXX) $(CXXFLAGS) $(CPPFLAGS) $(Objects) -o $(Appname) $(LDLIBS) #Rule: For every object file require a dependency file and a C++ file #1. Create the Folder #2. Create Dependency File #3. Create Object File $(ObjectsDir)/%.o: %.cpp mkdir -p $(@D) $(CXX) $(CXXFLAGS) $(CPPFLAGS) -MMD -MP -c $< -o $@ $(LDLIBS) clean: rm -rf $(ObjectsDir) run: ./$(Appname) #Include the dependency files Deps = $(Objects:%.o=%.d) -include $(Deps)
69,201,433
69,201,526
Finding the maximum value in a vector using recursion C++
I am trying to find the maximum value in a vector using recursion but I keep on getting a segmentation fault. I can't figure out the issue. Does anyone know why? int find_max(vector<int> integer_array, int i) { //variable i just keeps track of the index starting at 0 if(i == integer_array.size()-1) { return integer_array[i]; } return max(integer_array[i], find_max(integer_array, i++)); } //Example of a call: find_max(vector_array, 0); UPDATE: I know it's inefficient but this is just for practicing recursion...
I am assuming the vector always has elements. In the return statement, should be i+1 instead of i++: return max(integer_array[i], find_max(integer_array, i+1));. The problem with i++ is that this form would pass the value i to find_max for the second argument, and then increment. So you end up calling either return max(integer_array[i], find_max(integer_array, i)) or return max(integer_array[i+1], find_max(integer_array, i)), I forgot if the parameters were evaluated in order or not. In either case, it would not finish correctly. Also I would suggest const ref for find_max 1st argument: int find_max(const vector<int> &integer_array, int i). Otherwise it would copy the integer_array again and again without needing to modify the content. see reference. Thanks for the comment from paddy, very helpful in my future drafting answers.
69,201,644
69,202,331
a protobuf problem about descriptor and reflection
I have a problem. I want to make a very high frequency use of FieldDescriptor so I want to save FieldDescriptor address instead of calling FindFieldByName every time. I found that the same protobuf object would share the same meta, they have the same FileDescriptor object and FieldDescriptor object. Can I do that? enter image description here
Yes, this is safe (unless you are doing something funky). When working with the interfaces generated by protoc, descriptors can safely be treated as permanent global variables, shared across messages. It's a different matter when you are dealing with descriptors that come from other sources, like gRPC's reflection service for example. Even then, the lifetimes involved are generally straightforward.
69,201,935
69,238,031
OpenCV segmentation fault when converting video to PNG sequence
Converting to webm first causes the frame of segmentation fault failure to move to frame 1308, instead of 1301. My code: #include <iostream> #include <stdio.h> #include <stdlib.h> #include <opencv2/opencv.hpp> #include <opencv2/core.hpp> #include <opencv2/imgcodecs.hpp> #include <opencv2/highgui.hpp> using namespace std; using namespace cv; void conv_vid_png(string input_path, string output_path){ VideoCapture cap(input_path); int count = 0; if(!cap.isOpened()){ cout << "Error opening video stream or file" << endl; } while(1) { Mat frame; //Why the fuck does this use the stream insertion operator? // >> appears to both increment and store cap >> frame; //Break the loop when there are no more frames to capture if (frame.empty()) break; imwrite(output_path+"frame"+to_string(count)+".png", frame); cout << "frame " + to_string(count) + " processed" << endl; count++; } } int main() { string in_path = "./movie_type_files/vert_beach_short.mp4"; string out_path = "./tmp_png/"; conv_vid_png(in_path, out_path); //First, convert the video file to png sequence return 0; } Which uses the OpenCV VideoCapture object to write each frame of a video to PNGs. I did not have a problem with this same function in OpenCV for python. The segmentation fault happens at the same frame (1301) despite there ostensibly being nothing out of the ordinary about that frame. Thoughts on a solution? I'm currently using ffmpeg to convert the .mp4 to a webm to see if the issue persists. This is my first C++ program so I am struggling to self diagnose my problem. I followed a guide on diagnosing segmentation faults and have included the results I gathered below.
The segmentation fault actually happened in a following function. I thought I had exactly 1340 frames in this render, but it turns out some got lost in some processing I did, so the code in the original question was 100% correct. The segmentation fault was caused by a failure to read a file, ( I had forgot to pad zeros before the index of the frame). Since the frame was empty, when I used a pointer to access data that did not exist I got a segmentation fault.
69,202,158
69,202,462
Need help fixing this C++ code (Quadratic Formula solver)
When I execute the problem, the results often end up as "-nan' or "nan" I am new to programming so this is a bit confusing. Could use some help ` #include <iostream> #include <cmath> using namespace std; //Quadratic Equation int main() { //Variables double a,b,c,n,z,x1,x2,r; //Input cout<<"Quadartic Equation Calculator"<<endl<<endl; cout<<"What is you 'a' value?: "<<endl; cin>>a; cout<<"What is your 'b' value?: "<<endl; cin>>b; cout<<"What is your 'c' value?: "<<endl; cin>>c; //calculation n = -b; z = sqrt((b*b)-(4*a*c)); r= 2*a; x1 = (n+(z))/r; x2 = (n-(z))/r; //output cout<<"Your Solutions are: "<< x1 << " or "<< x2; return 0; } `
std::sqrt() in the <cmath> header expects its argument to be a positive number, in case it isn't, it will return nan which is what you are facing. It also raises the FE_INVALID floating point exception which you can verify after calling the std::sqrt() function using std::fetestexcept(FE_INVALID). In actual math, square roots of negative numbers result in complex numbers. Ordinary floating-point types like double which usually follow the IEEE-754 standard are not capable of representing complex numbers. For that, you need to use something like std::complex<double> which is actually capable of storing complex numbers inside it. Below is your code modified to utilize std::complex<double> and will properly print the real and imaginary part separately for square roots of negative real numbers instead of simply returning nan as it did before. #include <iostream> #include <complex> using namespace std; double abs_zero(double const x) { return x == 0 ? 0 : x; } int main() { // Variables complex<double> a, b, c, n, z, x1, x2, r; // Input cout << "Quadartic Equation Calculator" << endl << endl; cout << "What is your 'a' value?: " << endl; cin >> a; cout << "What is your 'b' value?: " << endl; cin >> b; cout << "What is your 'c' value?: " << endl; cin >> c; // Calculation n = -b; z = sqrt((b * b) - (complex<double>(4, 0) * a * c)); r = complex<double>(2, 0) * a; x1 = (n + z) / r; x2 = (n - z) / r; x1 = complex<double>(abs_zero(real(x1)), abs_zero(imag(x1))); x2 = complex<double>(abs_zero(real(x2)), abs_zero(imag(x2))); // Output if (imag(x1) == 0) cout << "Your Solutions are: " << real(x1) << " or "<< real(x2) << endl; else cout << "Your Solutions are: " << x1 << " or " << x2 << endl; } In case you'd like to try it out yourself, here you are: Demo
69,202,252
69,217,967
ncurses library I want to know why colors cannot be drawn
[I'm Japanese using google translate] The presentation code is void Renderer (); the function part, why can't I draw the color? I don't know the cause. Also, the addch (); function can draw colors normally. OS: Ubuntu Reference site A: https://www.linuxjournal.com/content/programming-color-ncurses Reference site B: https://www.linuxjournal.com/content/about-ncurses-colors-0 Screen.cpp #include "../header/Screen.hpp" #include "../header/Character.hpp" #include "../header/Color.hpp" #include "../header/Vector.hpp" #include "../header/Screen.hpp" // ######################## コンストラクタ ######################## Screen::Screen() { //ウインドウ初期化 getmaxyx(stdscr,windowSize.y,windowSize.x); window = newpad(windowSize.y,windowSize.x); start_color(); //カラーを有効化 prefresh(window,0,0,0,0,windowSize.y,windowSize.x); size.x = windowSize.x; size.y = windowSize.y; maxSize = size.x * size.y; stage = std::make_unique<std::vector<Character>>(size.x * size.y); for(std::vector<Character>::iterator itr = stage->begin(); itr != stage->end(); itr++) { itr->chr = ' '; itr->color = Color::NONE; itr->type = 0; } } // ######################## 画面サイズ更新 ######################## void Screen::UpdateScreen() { //画面サイズを取得 getmaxyx(stdscr,windowSize.y,windowSize.x); //前のウインドウサイズをより大きければ要素を代入 if((windowSize.x * windowSize.y) > maxSize) { maxSize = windowSize.x * windowSize.y; size.x = windowSize.x; size.y = windowSize.y; for(int i = 0; i< (windowSize.x * windowSize.y); i++) { stage->emplace_back(Character{Color::NONE,' ',0}); } } } // ######################## Update ######################## void Screen::Update() { UpdateScreen(); //画面サイズを更新 } // ######################## 文字設定 ######################## void Screen::Input(int x,int y,Character c) { stage->at((y * size.x) + x) = c; } // ######################## 文字削除 ######################## void Screen::Delete(int x,int y) { stage->at((y * size.x) + x).chr = ' '; stage->at((y * size.x) + x).color = Color::NONE; stage->at((y * size.x) + x).type = 0; } // ######################## Renderer ######################## void Screen::Renderer()const { for(int y = 0; y < size.y; y++) { for(int x = 0; x < size.x; x++) { // attron(COLOR_PAIR(stage->at((y * size.x) + x).color)); attron(COLOR_PAIR(16)); mvwaddch(window,y,x,stage->at((y * size.x) + x).chr); //addch(stage->at((y * size.x) + x).chr); //attrset(COLOR_PAIR(16)); //attroff(stage->at((y * size.x) + x).type); // attroff(COLOR_PAIR(stage->at((y * size.x) + x).color)); } } prefresh(window,0,0,0,0,windowSize.y,windowSize.x); } // ######################## デストラクタ ######################## Screen::~Screen() { }
wattron(window,COLOR_PAIR(stage->at((y * size.x) + wattroff(window,COLOR_PAIR(stage->at((y * size.x) + When using windows, it was necessary to use the wattron() and wattroff() functions instead of the attron() and attroff() functions. The code inside the comment part of the question sentence needs to be modified as follows for the for statement. for(int y = 0; y < size.y; y++) { for(int x = 0; x < size.x; x++) { wattron(window,COLOR_PAIR(stage->at((y * size.x) + x).color)); mvwaddch(window,y,x,stage->at((y * size.x) + x).chr); wattroff(window,COLOR_PAIR(stage->at((y * size.x) + x).color)); } }
69,202,767
69,211,237
Can imdecode be used to clipboard image?
I want to use the Windows clipboard image data in OpenCV without using a temporary file. Can I use imdecode for this? I tried this but Mat was empty: if(!IsClipboardFormatAvailable(CF_DIB)) return; OpenClipboard(NULL); HGLOBAL clipboard = GetClipboardData(CF_DIB); if(clipboard){ char* data = (char*)GlobalLock(clipboard); Mat buf = Mat(1, GlobalSize(clipboard), CV_8UC1, data, Mat::AUTO_STEP); Mat mat = imdecode(buf, IMREAD_UNCHANGED); GlobalUnlock(clipboard); } CloseClipboard();
You should be able to use CF_BITMAP to get the handle to HBITMAP. Then use GetDIBits to copy HBITMAP to cv::Mat memory. If for some reason CF_BITMAP is not available, see this example for CF_DIB backup, or check to see which format is available. void copy() { cv::Mat mat; HBITMAP hbitmap = nullptr; if (!::OpenClipboard(nullptr)) return; if (IsClipboardFormatAvailable(CF_BITMAP)) hbitmap = (HBITMAP)GetClipboardData(CF_BITMAP); if(!hbitmap && IsClipboardFormatAvailable(CF_DIB)) { HANDLE handle = GetClipboardData(CF_DIB); LPVOID hmem = GlobalLock(handle); if (hmem) { BITMAPINFO* bmpinfo = (BITMAPINFO*)hmem; int offset = (bmpinfo->bmiHeader.biBitCount > 8) ? 0 : sizeof(RGBQUAD) * (1 << bmpinfo->bmiHeader.biBitCount); BYTE* bits = (BYTE*)(bmpinfo)+bmpinfo->bmiHeader.biSize + offset; HDC hdc = ::GetDC(0); hbitmap = CreateDIBitmap(hdc, &bmpinfo->bmiHeader, CBM_INIT, bits, bmpinfo, DIB_RGB_COLORS); ::ReleaseDC(0, hdc); GlobalUnlock(hmem); } } if (hbitmap) { BITMAP bm; ::GetObject(hbitmap, sizeof(bm), &bm); int cx = bm.bmWidth; int cy = bm.bmHeight; if (bm.bmBitsPixel == 32) { mat.create(cy, cx, CV_8UC4); BITMAPINFOHEADER bi = { sizeof(bi), cx, -cy, 1, 32, BI_RGB }; GetDIBits(hdc, hbitmap, 0, cy, mat.data, (BITMAPINFO*)&bi, DIB_RGB_COLORS); } } CloseClipboard(); }
69,203,198
69,203,277
error: expected ‘#pragma omp’ clause before ‘{’ token
I have a stack. Each time I pop one element from it, handle this element and determine whether the element should be pushed back to the stack according to some results. The code is like the following. I used the OpenMP task construct to achieve parallelism because the handling processes of different elements are independent. But I got error: expected ‘#pragma omp’ clause before ‘{’ token for both the lines of #pragma omp parallel and #pragma omp single. I have no idea about the reasons. And I am also curious about the correctness of my usage of the OpenMP task construct. int processing_ele; omp_set_num_threads(2); #pragma omp parallel { #pragma omp single { while (!stack_ele.empty()) { // pop int processing_ele = stack_edge_id.top(); stack_ele.pop(); // handle #pragma omp task Test(processing_ele); if (global_res[processing_ele].need_to_push) { stack_ele.push(processing_elec); } } } }
In OpenMP specification you can read The syntax of an OpenMP directive is as follows: #pragma omp directive-name [clause[ [,] clause] ... ] new-line Please observe the new line at the end of the directive, so { have to be in a new line: #pragma omp parallel { #pragma omp single { or #pragma omp parallel #pragma omp single {
69,203,400
69,215,303
Return without memory leak
I try to write a function which converts a char* to a wchar_t* to simplify multiple steps in my program. wchar_t* ConvertToWString(char* str) { size_t newStrSize = strlen(str) + 1; wchar_t* newWStr = new wchar_t[newStrSize]; size_t convertedChars = 0; mbstowcs_s(&convertedChars, newWStr , newStrSize, str, _TRUNCATE); return newWStr; // I know i need to call "delete[] newWStr;" but then I can't return the converted string... } The function works but it is obviously memory leaking. Does someone know another way how to convert a char* to a wchar_t*? My issue is that the function needs to handle different string lengths. Right now I am using a workaround with a fixed buffer but that can't be the only solution: wchar_t* ConvertToWStringUgly(char* str) { wchar_t buffer[1024]; // fixed array for 1023 wchars size_t newStrSize = strlen(str) + 1; size_t convertedChars = 0; mbstowcs_s(&convertedChars, buffer, newStrSize, str, _TRUNCATE); return buffer; // This is working but not really a good way }
Classic. Use the C++ power ! ... Destructors freeing allocated memory Instead of your wchar_t buffer [1024]; why not declare and use a Wstr class, looking approximately like this (maybe malloc and free to used instead of new and delete ?): class Wstr { public : Wstr () : val_ ((wchar_t*) NULL), size_ (0) {} ~Wstr () { if (val_ != (wchar_t*)NULL) { delete[] val_; val_ = (wchar_t*)NULL; } } Wstr& operator = (const char*& str) { size_ = strlen(str) + 1; if (val_ != (wchar_t*) NULL) { delete [] val_; val_ = (wchar_t*) NULL; } size_t newStrSize = strlen(str) + 1; size_t convertedChars = 0; mbstowcs_s(&convertedChars, val_, newStrSize, str, _TRUNCATE); size_ = newStrSize; return *this; } //.. copy cons, op =, op ==, op != to be written wchar_t* val_; size_t size_; };
69,203,795
69,204,105
non-const lvalue reference to type 'pair<...>' cannot bind to a temporary of type 'pair<...>'
I'm trying to get a reference to the emplaced item using auto& syntax, but it fails to compile with above error. How can I get reference to emplaced item in this case? I've attempted to use const auto& but the object seems invoking destructor on my actual app so thus it seems to be a fake reference at best. #include <string> #include <unordered_map> class Connection { public: bool foo{}; }; int main() { std::unordered_map<std::string, Connection> connections; auto& [connection, inserted] = connections.try_emplace("test"); }
That's because try_emplace returns a pair<iterator, bool>, which is a temporary, NOT a reference to the inserted element. See description on cppreference After emplacing, you could say auto& elem = connections["test"]; or auto [connection, inserted] = connections.try_emplace("test"); auto& elem = *connection; for example, to get a reference to the element. The first variant returns a reference to the actual value associated with the key test, whereas the second one returns a reference to the map element, which is a pair<const key_type, mapped_type>, i.e. the first version essentially returns second of said pair directly. const auto& compiles because it is legal to declare a const reference to a temporary, but not a non-const lvalue reference.
69,204,086
69,205,338
May types be defined in `decltype` or `sizeof` expressions in C++20?
Since C++20 lambda functions are allowed in unevaluated contexts, and in particular they should be allowed inside decltype and sizeof expressions. In its turn, lambdas can define some types in their bodies and possible return objects of these types, for example: using T = decltype( []{ struct S{}; return S{}; } ); [[maybe_unused]] constexpr auto N = sizeof( []{ struct S{}; return S{}; } ); Clang accepts this code, but GCC emits the errors: error: types may not be defined in 'decltype' expressions 1 | using T = decltype( []{ struct S{}; return S{}; } ); error: types may not be defined in 'sizeof' expressions 4 | = sizeof( []{ struct S{}; return S{}; } ); Demo: https://gcc.godbolt.org/z/9aY1KWfbq Which one of the compilers is right here?
The restrictions on lambdas in unevaluated contexts that were removed as of P0315R4 means this is not prohibited (albeit a corner case), and thus arguably GCC has a bug here. Particularly the following discussion from the paper is relevant here: Furthermore, some questions were raised on the Core reflector regarding redeclarations like this: template <int N> static void k(decltype([]{ return 0; }())); template <int N> static void k(decltype([]{ return 0; }())); // okay template <int N> static void k(int); // okay These should be valid redeclarations, since the lambda expressions are evaluated, and they neither contain a template parameter in their body nor are part of a full-expression that contains one. Hence, the lambda-expression does not need to appear in the signature of the function, and the behavior is equivalent to this, without requiring any special wording: struct lambda { auto operator()() const { return 0; } }; template <int N> static void k(decltype(lambda{}())); template <int N> static void k(decltype(lambda{}())); // okay today template <int N> static void k(int); // okay today The same argument holds also for the OP's example, and (arguably) "the behavior is equivalent to this, without requiring any special wording": struct lambda { auto operator()() const { struct S{}; return S{}; } }; using T = decltype(lambda{}); [[maybe_unused]] constexpr auto N = sizeof( []{ struct S{}; return S{}; } ); Note that the sizeof is simpler, as you are querying the size of the captureless lambda's closure type, and not the size of the local struct S.
69,204,119
69,208,173
Conversion of date from human-readable format to epoch fails
I'd like to create a program that converts the date of a specific human-readable format to epoch. So far I have the following code the first part of which creates this human-readable format and the second one converts it to epoch. #include <time.h> #include <iostream> #include <ctime> #include <string> #include <cstring> using namespace std; int main(int argc, char const *argv[]) { time_t timeNow; struct tm *ltm = NULL; time(&timeNow); ltm = localtime(&timeNow); char buffer[100]; strftime(buffer, sizeof(buffer), "%c %Z", ltm); cout << "human readable timestamp is " << buffer << endl; std::tm tmNow; memset(&tmNow, 0, sizeof(tmNow)); strptime(buffer, "%c %Z", &tmNow); cout << "epoch timestamp is " << mktime(&tmNow) << endl; return 0; } So the printouts I get are the following : human readable timestamp is Thu Sep 16 10:23:06 2021 EEST epoch timestamp is 1631780586 My time zone is EEST as one can see but the epoch one is wrong because it is one hour ahead. The correct should have been 1631776986. I assume I'm doing wrong something with the local time. I've found third-party libraries examples like boost or poco that do this conversion, but I'd prefer the above conversion to be done by using native C++. Does anyone see what I'm missing?
The C timing/calendrical API is very difficult to use correctly (which is why C++ is moving away from it). From the C standard: The value of tm_isdst is positive if Daylight Saving Time is in effect, zero if Daylight Saving Time is not in effect, and negative if the information is not available. Set tmNow.tm_isdst = -1; prior to the call to mktime.
69,205,046
69,206,177
How to deal with declaration of the primitive type without the initial value known (C++)?
In some cases it happens for me to declare a variable without knowing its value first like: int a; if (c1) { a = 1; } else if (c2) { a = 2; } else if (c3) { a = -3; } do_something_with(a); Is it the standard professional practice to assign some clearly wrong value like -1000 anyway (making potential bugs more reproducible) or it is preferred not to add the code that does nothing useful as long as there are no bugs? From one side, looks reasonable to remove randomness, from the other side, magical and even "clearly wrong" numbers somehow do not look attractive. In many cases it is possible to declare when the value is first known, or use a ternary operator, but here we would need it nested so also rather clumsy. Declaring inside the block would move the variable out of the scope prematurely. Or would this case justify the usage of std::optional<int> a and assert(a) later, making sure we have the value? EDIT: The bugs I am talking about would occur if suddenly all 3 conditions are false that should "absolutely never happen".
I would introduce a default value. I'm usually using MAX value of the type for this. Shortest you can do this with the ternary operator like this: #include <climits> int a = c1 ? 1 : c2 ? 2 : c3 ? -3 : INT_MAX; do_something_with(a);
69,205,586
69,208,379
Move layout to another layout in Qt5
I have a custom container widget in Qt5 which has a QFrame without a layout. I use setLayout on QFrame which works fine but sometimes I want to transfer an existing layout which contains widgets and other layouts to that QFrame as layout. Is that even possible in Qt5 to transfer layouts already added with addLayout?
No problem. Just make the layout the layout of the target widget with setLayout(). The widgets contained will be reparented automatically. void MainWindow::moveLayout() { // Move the layout from ui->g0 to ui->g1 and vice versa // every time you call moveLayout static int toggle = 0; QLayout* l; QWidget* w; if (toggle == 0) { l = ui->g0->layout(); w = ui->g1; } else { l = ui->g1->layout(); w = ui->g0; } if (w->layout()) { // Hack to clean target widget QWidget z; z.setLayout(w->layout()); } w->setLayout(l); toggle = 1 - toggle; }
69,205,644
69,205,673
How to prevent the creation of an object in C++
i'm learning how to make classes and i want to prevent my user from creating an object without providing a variable. The problem is that i don't know how to procede in order to do that. here's my code : class KoalaNurse { public: int id; // the var that i need to provide in order to create a new object if it's not provided it wont create the object void giveDrug(std::string gato, SickKoala *patient) { patient->takeDrug(gato); } ~KoalaNurse() { std::cout << "Nurse " << id << ": Finally some rest !" << std::endl; } }; ty for any help !
You need to define your own constructor in order for the compiler not to create the default one. KoalaNurse (int some_value) { //your code }; Another option is to use keyword delete in order to prevent creating default constructor: KoalaNurse() = delete;
69,205,683
69,209,650
c++17 how to create a template instance with a non-type template
I want to create a body with a different part, and if I know the part's name, I can create the corresponding instance with a factory.Just as below: template<typename Part> class Body {}; class Part1 {}; class Part2 {}; enum class E { part1, part2, }; template<E e> class Factory { public: static unique_ptr<Body<>> create() { if (e == E::part1) { return make_unique<Body<Part1>>(); } else { return make_unique<Body<Part2>>(); } } }; int main() { auto f=Factory<E::part1>(); return 0; } Certainly it fails at compile time,so how could I get my porpuse?
There's nothing here with a non-type template argument, so your title is confusing. I assume your compiler error is complaining about Body<> Well, that's an error. Body is not a type, but a template. It needs an argument and there is no default. The code wants it to be a Body<Part1> or a Body<Part2> but there is no such thing as a "Body of anything" as you implied. You can have a type that holds either type by using a variant. For example, using BodyPart = std::variant<Body<Part1>,Body<Part2>>; But you'll have to learn how to use that value effectively (best with visitors), as it's not the same as a polymorphic type nor a generic (compile time) template.
69,205,878
69,206,944
How Do I Sort A Stack Alphabetically in C++?
I'm new to C++, and I do not understand stacks that well. I tried following some tutorials to sort Stack1 using recursion, but nothing has been working or it is solely focused on arrays containing integers. I also tried sorting the Names array directly, but it does not work. How do I go about sorting my Names array for my Stack1 so in a non-complex manner (since I am new and do not understand it that well)? Here's my code: //Necessary libraries #include <iomanip> #include <iostream> #include <stack> #include <algorithm> using namespace std; //Main CPP Function int main() { //Name and Surname std::string Names[] = { "Sam", "John", "Simon", "Sarah", "Mat", "Nick", "Isaac", "Anna", "Daniel", "Aaron", "Jack", "Kathrine " };std::sort(std::begin(Names), std::end(Names)); std::string Surnames[] = { "Williams", "Phoenix", "Johnson", "Khosa", "Jackon", "Roberts", "Wayne", "Mishima", "Rose", "Black", "Mohamed", "Bruckner" }; //Score Array int Score[] = { 60, 85, 75, 81, 38, 26, 74, 34, 64, 83, 27, 42 }; //Variable decleration needed for if statements int l; int k; //Calculates array size l = sizeof(Names) / sizeof(Names[0]); k = sizeof(Surnames) / sizeof(Surnames[0]); //------------------------------- Stack One --------------------------------------// //var declaration stack <string> Stack1; stack <int> Score1; cout << "Stack One" << endl; //sort stack one alphabetically by name //whilst our Names array is not empty, we will push it into the stack for (int i = 0; i < l; i++) { //pushes Names, Surnames and Scores to first stack Stack1.push(Names[i]); Stack1.push(Surnames[i]); Score1.push(Score[i]); //prints Names, Surnames and Scores for the first stack while (!Stack1.empty()){ cout << "\t" << setw(20) << Stack1.top() << "\t" << Score1.top() << endl; //stops the printing from printing in an endless loop Stack1.pop(); Score1.pop(); } } return 0; } As mentioned in the comments, it is required by an assignment that I sort my stacks. Here is the assignment text for more understanding:
If the underlying container for the stack has its data stored in consecutive memory, which is true for a std::vector or a std::deque, the sorting is ultra simple. You can simply sort the underlying container. That is really easy. The std::deque is the default underlying container. So, this approach will work in most cases. Please see the below small example: #include <iostream> #include <stack> #include <deque> #include <algorithm> #include <functional> int main() { // Define a stack and initialize it with some values std::stack<int> myStack(std::deque<int>{2,1,4,3,10,20,32,25}); // Get iterator to begin end end of tsakcs underlying container int* endOfStack = &myStack.top() + 1; int* beginOfStack = endOfStack - myStack.size(); // Sort it std::sort(beginOfStack, endOfStack, std::greater<int>()); // Output stack content for (; not myStack.empty(); myStack.pop()) std::cout << myStack.top() << '\n'; return 0; } My guess is that you wanted some recursive solution, because you mentioned something like that. With a sortable or already sorted helper container, also a recursive solution is possible. #include <iostream> #include <stack> #include <deque> #include <algorithm> #include <functional> #include <set> // Recursive sort function using a helper container void sortStackRecursive(std::stack<int>& myStack, std::multiset<int> data) { // Check for end of recursion if (myStack.empty()) { // All elements have been popped of the stacked, sorted and put in the multiset // Now push them on the stack again in sorted order for (const int value : data) myStack.push(value); return; } else { // Add top of stack element into multiset data.insert(myStack.top()); myStack.pop(); // Self call sortStackRecursive(myStack,data); } } void sortStack(std::stack<int>& myStack) { std::multiset<int> data{}; sortStackRecursive(myStack,data); } int main() { // Define a stack and initialize it with some values std::stack<int> myStack(std::deque<int>{2,1,4,3,10,20,32,25}); // Sort it sortStack(myStack); // Output stack content for (; not myStack.empty(); myStack.pop()) std::cout << myStack.top() << '\n'; return 0; } But, as per my final guess, what the instructor really wants is that you just use stacks, without any helper container. This can also be achieved by using one temporary stack. Please see: #include <iostream> #include <stack> #include <deque> #include <algorithm> // Sort a stack, with the help of one temporary stack void sortStack(std::stack<int>& myStack) { // Define a temporary stack std::stack<int> tempStack; // As long as there are values on the original stack while (not myStack.empty()) { // Get the top of the stack value and remember it int value = myStack.top(); myStack.pop(); // And now. As long as there are values on our temporary stack // and the top value of the temporary stack is smaller than the value // on the original stack while(not tempStack.empty() and tempStack.top() < value) { // Then exchange the current top elements myStack.push(tempStack.top()); tempStack.pop(); } // And put the original greater value back on the top of the stack tempStack.push(value); } // If there are still bigger values on the temporary stack while (not tempStack.empty()) { // the push them back on the original stack myStack.push(tempStack.top()); tempStack.pop(); } } int main() { // Define a stack and initialize it with some values std::stack<int> myStack(std::deque<int>{2,1,4,3,10,20,32,25}); // Sort it sortStack(myStack); // Output stack content for (; not myStack.empty(); myStack.pop()) std::cout << myStack.top() << '\n'; return 0; }
69,205,893
69,206,075
Does c++ standard allow to call std::align with zero size and obtain a past-the-end pointer?
Does std::align allow to be called with zero size and obtain an aligned pointer that may be a past-the-end pointer? For example: #include <cstdio> #include <memory> int main() { alignas(16) char buffer[16]; printf("buffer: %p ~ %p\n", static_cast<void*>(buffer), static_cast<void*>(buffer + sizeof(buffer))); void* start = buffer + 10; std::size_t space = 6; printf("start=%p space=%zu\n", start, space); void* result = std::align(8, 0, start, space); // call with size=0 printf("result=%p start=%p space=%zu\n", result, start, space); // result is a pase-the-end pointer }
Does c++ standard allow to call std::align with zero size Yes; there is no precondition disallowing zero size. and obtain a past-the-end pointer? Obtaining a one-past-the-end pointer is allowed.
69,206,044
69,281,389
SWIG/Python: Unable to access referenced parameter in Python callback
In SWIG, I've got a wrapped C++ base class that is inherited in Python. The C++ side invokes callbacks on the Python derived class, which works fine. Unfortunately, one of the parameters of the callback is passed as reference. Accessing this reference yields: Fatal unhandled exception: SWIG director method error. Error detected when calling 'Base.Start' test.i %module(directors="1", allprotected="1") test %feature("director") Base; class Base { public: virtual bool Start(const Property& config) = 0; // PASSED AS REFERENCE }; enum PropertyType{PT_REAL, PT_STRING}; class Property { public: PropertyType GetType() const; int GetSize() const; }; In Python, Start is correctly callback/invoked. Unfortunately, invoking GetType() or GetSize() yields the error above. Invoking functions of parameters passed as pointer is going fine. import test class PyClient(test.Base): def Start(self, config): config_size = config.GetSize() // YIELDS ERROR config_type = config.GetType() // YIELDS ERROR return True I guess I need to convert the parameter Property from a reference to a pointer, but it is unclear to me how this works in SWIG. UPDATE It seems the argument in the invoked callback has a different underlying type than when created on the Python side. def Start(self, config): prop_test = test.Property() type_test = prop_test.GetType() #FINE type_test2 = config.GetType() # ERROR When a Property (prop_test) is created on the Python side in Start(), its type is <mds.Property; proxy of <Swig Object of type 'Property *' at 0x000001CC24DA3D80> > Whereas the passed property has a type <Swig Object of type 'Base::Property *' at 0x000001CC24CBE1E0> I wonder whether this is expected, or this might lead to the underlying issue. Swig 4.0.2 Any help would be really appreciated. Ben
Ah, I finally figured it out, turned out that the Property class was in a different namespace in the C++ code, but not in the SWIG interface file. By setting the right namespace, a proxy was generated and everything worked fine.
69,206,062
69,206,114
How To Output Characters Using Linked Lists?
#include <iostream> using namespace std; class FloatList { private: // Declare a structure for the list struct ListNode { float value; struct ListNode *next; }; ListNode *head; // List head pointer public: FloatList(); // Constructor void appendNode(float num); }; FloatList::FloatList() { head = NULL; } void FloatList::appendNode(float num) { ListNode *newNode, *nodePtr; // Allocate a new node & store num newNode = new ListNode; newNode->value = num; newNode->next = NULL; // If there are no nodes in the list // make newNode the first node if (!head) head = newNode; else // Otherwise, insert newNode at end { // Initialize nodePtr to head of list nodePtr = head; // Find the last node in the list while (nodePtr->next) nodePtr = nodePtr->next; // Insert newNode as the last node nodePtr->next = newNode; } cout << num << " has been APPENDED!" << endl; } int main() { FloatList list; list.appendNode(2.5); list.appendNode(7.9); list.appendNode(12.6); } INSTRUCTIONS : Convert the above Linked List ADT with Append Operation into a Linked List Template for it to be capable of handling data of different data types. Once your program is complete, change your main program to the following: int main() { FloatList list; list.appendNode('a'); list.appendNode('b'); list.appendNode('c'); cout << "Successful Append!" << endl; } I am able to print the floats (2.5) (7.9) and (12.6), but I cannot edit the program to be able to print 'a', 'b', and 'c' This is the expected output: a has been APPENDED! b has been APPENDED! c has been APPENDED! Successful Append!
If you wanted to make it work for string types, or char types, you would have to turn your linked list into templated class. Look at your definition of node: struct ListNode { float value; struct ListNode *next; }; You defined float as value, so how do you expect it co hold char type? I changed your linkedlist so now it can take any type you desire: #include <iostream> using namespace std; template <typename T> class FloatList { private: // Declare a structure for the list struct ListNode { T value; struct ListNode* next; }; ListNode* head; // List head pointer public: FloatList() { head = NULL; }// Constructor void appendNode(T num) { ListNode* newNode, * nodePtr; // Allocate a new node & store num newNode = new ListNode; newNode->value = num; newNode->next = NULL; // If there are no nodes in the list // make newNode the first node if (!head) head = newNode; else // Otherwise, insert newNode at end { // Initialize nodePtr to head of list nodePtr = head; // Find the last node in the list while (nodePtr->next) nodePtr = nodePtr->next; // Insert newNode as the last node nodePtr->next = newNode; } cout << num << " has been APPENDED!" << endl; } }; int main() { FloatList<float> list; list.appendNode(2.5); list.appendNode(7.9); list.appendNode(12.6); FloatList<char> char_list; char_list.appendNode('c'); char_list.appendNode('d'); char_list.appendNode('e'); } As your list is now templated class, you must specify what is the templated type: FloatList<float> list; The solution is really nice and simple, all you had to do is to change two things in your class definition: a) tell compiler that this class is templated template <typename T> class FloatList b) swap all floats into T (our desired type): float value; T value; void appendNode(float num) void appendNode(T num)
69,206,184
69,206,756
How can I use a QMap to store and look at my data?
I am new to QT started to try out some things with QMap as it seems like a useful tool. I already read some other forum threads but I wasnt able to answer my question. The user is supposed to add and edit different shapes via the GUI. For the shapes I first wrote an abstract base class: #ifndef BASE_H #define BASE_H #include <QListWidget> #include <QMap> class Base { protected: QVariantMap m_properties; QString m_key; void setKey(const QString& key){ this->m_key=key; } public: Base(){} virtual ~Base(){} QString key(){ return m_key; } void setProperty(QString key, QVariant variant){ m_properties[key]=variant; } virtual void toRTC()=0; }; #endif // BASE_H one example of a subclass is an ellipse with the following cpp file: #include "ellipse.h" Ellipse::Ellipse(int Start_x, int Start_y, int Rad_x, int Rad_y): rad_x(Rad_x), rad_y(Rad_y), start_x(Start_x), start_y(Start_y) { this->setKey("ellipse"); this->setProperty("radX", rad_x); this->setProperty("radY", rad_y); this->setProperty("startX", start_x); this->setProperty("startY", start_y); } void Ellipse::set_rad_x(int rad_x) { Base::setProperty("radX", rad_x); } void Ellipse::set_rad_y(int rad_y) { Base::setProperty("radY", rad_y); } void Ellipse::set_start_x(int start_x) { Base::setProperty("startX", start_x); } void Ellipse::set_start_y(int start_y) { Base::setProperty("startY", start_y); } int Ellipse::get_rad_x() { return m_properties["radX"].toInt(); } int Ellipse::get_rad_y() { return m_properties["radY"].toInt(); } int Ellipse::get_start_x() { return m_properties["startX"].toInt(); } int Ellipse::get_start_y() { return m_properties["startY"].toInt(); } First off, is this a correct approach for the cpp file? I feel my approach is vary laborious. In my main window file I thought about storing my data in a simple Vector QVector<Base *> data_storage; Ellipse *e_values = new Ellipse(ui->Ellipse_Value_start_x->value(),ui->Ellipse_Value_start_y->value(), ui->Ellipse_Value_rad_x->value(),ui->Ellipse_Value_rad_y->value()); data_storage.append(e_values); To load the data, I thought it would be a good idea to use the key to check which object of data_storage I want to load, but I don't really know how I can access the data which is connected to my key. if(data_storage[t]->key()=="ellipse"){ ui->Ellipse_Value_rad_x->setValue(data_storage[t]->) //how can I access the correct data? } I feel like I messed up the entire approach, like how to properly use keys, so how would I do that?
You need to declare all the behaviours you need in the base class. I don't see the need to have Base hold the data. E.g. if you need to be able to read and write the UI, there should be methods to do that. class Base { public: virtual ~Base() = default; virtual void toRTC() = 0; virtual QVariantMap properties() const = 0; virtual void writeUI(form_t * ui) const = 0; virtual void readUI(const form_t * ui) = 0; }; class Ellipse : public Base { int start_x; int start_y; int rad_x; int rad_y; public: void toRTC() final { /* ??? */ } QVariantMap properties() const final { return { { "radX", rad_x }, { "radY", rad_y }, { "startX", start_x }, { "startY", start_y } }; } void writeUI(form_t * ui) const final { ui->Ellipse_Value_rad_x->setValue(rad_x); ui->Ellipse_Value_rad_y->setValue(rad_y); ui->Ellipse_Value_start_x->setValue(start_x); ui->Ellipse_Value_start_y->setValue(start_y); } void readUI(const form_t * ui) final { rad_x = ui->Ellipse_Value_rad_x->value().toInt(); rad_y = ui->Ellipse_Value_rad_y->value().toInt(); start_x = ui->Ellipse_Value_start_x->value().toInt(); start_y = ui->Ellipse_Value_start_y->value().toInt(); } }; If you don't want to tie your shapes to the UI, you could define a visitor interface, with a visit method for each shape type. class ShapeVisitor { virtual void accept(Ellipse * ellipse) = 0; /* virtual void accept(Rectangle * rectangle) = 0; // etc.. */ }; class Base { public: virtual ~Base() = default; virtual void toRTC() = 0; virtual QVariantMap properties() const = 0; virtual void visit(ShapeVisitor & visitor) = 0; }; class Ellipse : public Base { public: int start_x; int start_y; int rad_x; int rad_y; void toRTC() final { /* ??? */ } QVariantMap properties() const final { return { { "radX", rad_x }, { "radY", rad_y }, { "startX", start_x }, { "startY", start_y } }; } void visit(ShapeVisitor & visitor) final { visitor.accept(this); // calls visitor::accept(Ellipse *) } }; class UIReadVisitor : public ShapeVisitor { form_t * ui void accept(Ellipse * ellipse) final { ellipse->rad_x = ui->Ellipse_Value_rad_x->value().toInt(); ellipse->rad_y = ui->Ellipse_Value_rad_y->value().toInt(); ellipse->start_x = ui->Ellipse_Value_start_x->value().toInt(); ellipse->start_y = ui->Ellipse_Value_start_y->value().toInt(); } } class UIWriteVisitor : public ShapeVisitor { form_t * ui; void accept(Ellipse * ellipse) final { ui->Ellipse_Value_rad_x->setValue(ellipse->rad_x); ui->Ellipse_Value_rad_y->setValue(ellipse->rad_y); ui->Ellipse_Value_start_x->setValue(ellipse->start_x); ui->Ellipse_Value_start_y->setValue(ellipse->start_y); } }