Storing derived classes in a vector of base class - vector

I have seen several versions of my question, but I still cannot find an answer that works. I have defined a base class called TwoPort and two derived classes called Reflector and Waveguide as follows:
#include <vector>
class TwoPort
{
public:
TwoPort() { yeast = ywest = 0.0; }
~TwoPort() {}
double getyeast() { return yeast; }
double getywest() { return ywest; }
virtual void step(double xeast, double xwest);
protected:
double yeast;
double ywest;
};
class Reflector :
public TwoPort
{
public:
Reflector() { Gamma = 0.0; }
~Reflector() {}
void step(double xeast, double xwest) override;
void setReflection(double G) { Gamma = G; }
private:
double Gamma;
};
class Waveguide :
public TwoPort
{
public:
Waveguide() { oldest = 0; }
~Waveguide() {}
void step(double xeast, double xwest) override;
void setDelay(unsigned int delay);
private:
std::vector<double> eastBuffer, westBuffer;
unsigned int oldest;
};
My goal is to create a vector containing a mixture of Reflectors and Waveguides. Based on the answers to previous questions like mine, I have tried a number of approaches, but so far none have worked. For example:
int main()
{
std::vector<std::unique_ptr<TwoPort>> tpcascade;
tpcascade.emplace_back(new Reflector);
tpcascade.emplace_back(new Waveguide);
tpcascade.emplace_back(new Reflector);
tpcascade[0]->setRefection(0.25);
}
In this case, the compiler does not recognize the setReflection method. So I tried this:
int main()
{
std::vector<std::unique_ptr<TwoPort>> tpcascade;
auto ref = std::make_unique<Reflector>();
ref->setReflection(0.25);
tpcascade.emplace_back(ref);
}
In this case I can set the reflection but I get a lengthy and complex error message about the emplace statement.
Help!

Did some research and tried a variation on the second approach above:
int main()
{
std::vector<std::unique_ptr<TwoPort>> tpcascade;
auto ref = std::make_unique<Reflector>();
ref->setReflection(0.25);
tpcascade.push_back(std::move(ref));
}
Switching to shared_ptr seems to work too, and is a bit cleaner:
int main()
{
std::vector<std::shared_ptr<TwoPort>> tpcascade;
auto ref = std::make_shared<Reflector>();
ref->setReflection(0.25);
tpcascade.push_back(ref);
}
This also seems to work, but seems risky to me:
tpcascade.push_back(std::make_shared<Reflector>());
std::dynamic_pointer_cast<Reflector>(tpcascade[0])->setReflection(0.25);

Related

Why std::vector of pointers avoid deconstruction bugs?

In one of my project I managed to fix a bug switching from a std::vector of objects to a std::vector of pointers to the object. Using the debugger I found that the error occurred when I was calling the std::vector<T,Allocator>::clear that it is supposed to destroy the objects stored in the vector. I am happy I solved the issue but I would like to know why I was able to!
Here I attach the code incriminated:
#include <vector>
#include <memory>
#include <string>
class Base
{
public:
Base(int a);
Base(const Base& o)=default;
Base& operator=(const Base& o)=default;
Base(Base&& o)=default;
Base& operator=(Base&& o)=default;
virtual ~Base()=default;
virtual void Do();
};
class Derived: public Base
{
private:
std::string b;
public:
Derived(int a, std::string& b) : Base(a), b(b) {}
};
//Other derived classes from Base overriding Do
class Main{
private:
std::vector<Derived> v;
public:
Main();
void Do(int i, std::string& b){
/*
if something happens
v.emplace_back(a, b);// push_back equivalently for our purpose
if something else happens
v.erase(iterator)
*/
}
void reset(){
v.clear();
}
};
class Main1{
private:
std::vector<std::unique_ptr<Derived>> v;
public:
Main1();
void Do(int i, std::string& b){
/*
if something happens
v.push_back(std::unique_ptr<Derived>(new Derived(i, b)));
if something else happens
v.erase(iterator)
*/
}
void reset(){
v.clear();
}
};
int main()
{
Main m;
for(int i=0; i<101; ++i){
//something
m.Do(i, b);
//something
if(i%10==0)
m.reset(); //The bug is here. If I use Main1 everything runs smoothly
}
return 0;
}
This is a simplified version of the code that creates me problem. I hope that the detail are enough to give the correct contest for the answer.
The debugger points me deep in the code defining what a deconstructor does reporting a segmentation fault, and personally I cannot understand what that code does.
The compiler I am using is g++ 10.1 with the std=c++17 flag.

cppcheck out of bounds when it's not

When setting the size of a std::array in a class definition using a static const as the size, cppcheck doesn't know how large the array is. So it thinks I'm out of bounds when I'm not
Doing a #define seems to solve the problem so this is an academic question.
class A
{
A() : myArr()
{
myArr[0]=100;
}
static const int SOMEVAL = 4;
std::array<double, SOMEVAL+1> myArr;
int getVal() { return myArr[1]; };
}
int main(void)
{
A myA;
myA.getVal();
}
Any thoughts?
This was a defect in cppcheck:
https://trac.cppcheck.net/ticket/9202
Which has been fixed in the 1.89 release:
https://trac.cppcheck.net/changeset/121093658d788126d5f94792c4ea00447fdbb979/

Property values are lost (after each loop) when nesting libraries

I created 2 libraries to use in my Arduino code. One is a HwSwitch library, the other is a HwServo library which uses the HwSwitch library.
HwSwitch Library:
HwSwitch::HwSwitch(String switchName, int switchPort, int inputType, int pressedState)
{
Name = switchName;
SwitchPort = switchPort;
_pressedState = pressedState;
_lastCheckMillis = 0;
pinMode(switchPort, inputType);
_lastPinState = digitalRead(SwitchPort);
}
bool HwSwitch::IsPressed()
{
int currentPinState = GetPinState();
return currentPinState == _pressedState;
}
bool HwSwitch::SwitchStateChanged()
{
int currentPinState = GetPinState();
if (_lastPinState != currentPinState)
{
Serial.println("---");
Serial.println("1. Now: " + String(currentPinState) + " - Prev: " + String(_lastPinState));
_lastPinState = currentPinState;
Serial.println("2. Now: " + String(currentPinState) + " - Prev: " + String(_lastPinState));
return true;
}
return false;
}
int HwSwitch::GetPinState()
{
unsigned long ms = millis();
if ((ms - _lastCheckMillis) < 50)
{
return _lastPinState;
}
_lastCheckMillis = ms;
return digitalRead(SwitchPort);
}
HwServo Library:
HwServo::HwServo(int servoPort, int zeroPoint, HwSwitch limitSwitch)
{
_servo.attach(servoPort);
_servo.write(zeroPoint);
ServoPort = servoPort;
ZeroPoint = zeroPoint;
LimitSwitch = limitSwitch;
}
void HwServo::RotateUp()
{
_servo.write(ZeroPoint + UP);
}
void HwServo::RotateDown()
{
if (!LimitSwitch.IsPressed())
{
_servo.write(ZeroPoint + DOWN);
}
}
void HwServo::Stop()
{
_servo.write(ZeroPoint);
}
And this is how I initialized it in the Arduino code:
HwServo HwServos[] = {
HwServo(9, 94, HwSwitch("S1", 14, INPUT_PULLUP, HIGH)),
HwServo(5, 90, HwSwitch("S2", 8, INPUT_PULLUP, HIGH)),
};
void setup() { }
void loop() {
for(int i = 0; i < 2; i++)
{
HwServo hwServo = HwServos[i];
if (hwServo.LimitSwitch.SwitchStateChanged())
{
SendSwitchStateUpdate(hwServo.LimitSwitch);
if (hwServo.LimitSwitch.IsPressed())
{
hwServo.Stop();
}
}
}
}
Now finally to the problem! As you can see in the HwSwitch library I output some data using Serial.println. Here I can see that _lastPinState is successfully updated, but gets reset after every loop. However, when I create a HwSwitch directly and use it, _lastPinState is not reset. In other words, the resetting of the value only seems to occur when the HwSwitch library is used inside the HwServo library.
Appearently this has something to do with the pointers? I am probably initializing my classes incorrectly, but I have no idea how to fix it. Anyone that can help with (and preferably explain) this issue?
I don't have my Arduino on me right now, but I took look and re-wrote your code, added the omitted constructors at my best guess, and got it to compile. There were some things which needed corrected. I'm sure there are other ways, but this is what I did.
For complete code, go here.
First, I created some pointers to objects I'd like to stick around, like so:
HwServo *HwServos[2];
HwSwitch *s1;
HwSwitch *s2;
HwServo *sv1;
HwServo *sv2;
Now each is reserved in memory on the Arduino.
Now, construct the objects in setup():
void setup() {
s1 = new HwSwitch("S1", 14, INPUT_PULLUP, HIGH);
s2 = new HwSwitch("S2", 8, INPUT_PULLUP, HIGH);
sv1 = new HwServo(9, 94, *s1);
sv2 = new HwServo(5, 90, *s2);
//Now, since you're going through an array:
HwServos[0] = sv1;
HwServos[1] = sv2;
}
Use that setup function!!! Maybe not always necessary, or in some cases even recommended, but it's nice to collect things which only need created once there, especially is this case.
Note that new was not used inside the scope of either object, but rather in the scope of the program... So no fancy destructors in your objects are required. Normally, you'd worry about deleting them all before program termination (or whenever best suited), but in Arduino's case, it'll just lose power and kill everything anyway.
You should change your class definitions to this:
class HwSwitch {
public:
String Name;
int SwitchPort;
int _pressedState;
int _lastCheckMillis;
int _lastPinState;
HwSwitch(String, int, int, int);
bool IsPressed();
bool SwitchStateChanged();
int GetPinState();
};
class HwServo {
public:
HwServo();
HwServo(int, int, HwSwitch &);
int ServoPort;
int ZeroPoint;
HwSwitch & LimitSwitch;
void RotateUp();
void RotateDown();
void Stop();
Servo _servo;
};
Note: I made everything public, feel free to move private stuff back to private if you wish.
I changed the constructors to:
HwSwitch::HwSwitch(String switchName, int switchPort, int inputType, int pressedState)
{
Name = switchName;
SwitchPort = switchPort;
_pressedState = pressedState;
_lastCheckMillis = 0;
pinMode(switchPort, inputType);
_lastPinState = digitalRead(SwitchPort);
}
HwServo::HwServo(int servoPort, int zeroPoint, HwSwitch &limitSwitch)
{
_servo.attach(servoPort);
_servo.write(zeroPoint);
ServoPort = servoPort;
ZeroPoint = zeroPoint;
LimitSwitch = limitSwitch;
}
And I modified loop() like so:
void loop() {
// put your main code here, to run repeatedly:
for(int i = 0; i < 2; i++)
{
if (HwServos[i]->LimitSwitch.SwitchStateChanged())
{
SendSwitchStateUpdate(HwServos[i]->LimitSwitch);
if (HwServos[i]->LimitSwitch.IsPressed())
{
HwServos[i]->Stop();
}
}
}
}

QML SectionScroller and QList<QObject*>

I use QList<QObject*> as a model in my app. As there might be a lot of elements, I decided to use SectionScroller. When I try to scroll using the SectionScroller I'm getting a
Error: Unable to assign [undefined] to QString
What am I doing wrong?
My ListView is:
ListView
{
id: irrview
width: parent.width
model: irregulars.db // QList<QObject*>
anchors.top: caption.bottom
anchors.bottom: parent.bottom
clip: true
section.criteria: ViewSection.FirstCharacter
section.property: "form0"
section.delegate: Item {height: 10; width: parent.width; Text { text: section } } // for testing purposes
delegate: Rectangle
{
/**/
}
}
Thanks
EDIT: more code:
the irregulars header
class IrregularListWrapper : public QObject
{
Q_OBJECT
Q_PROPERTY(QList<QObject*> db READ getdb NOTIFY langChanged)
Q_ENUMS(Language)
public:
enum Language
{
English = 0,
German = 1
};
IrregularListWrapper() : db(0) { setLang(German); }
~IrregularListWrapper() { delete db; }
QList<QObject*> getdb() const { return *db; }
Q_INVOKABLE void changeLang(Language l) { delete db; setLang(l); }
signals:
void langChanged();
protected:
void setLang(Language);
QList<QObject*> * db;
};
and the body of a function
void IrregularListWrapper::setLang(Language l)
{
switch (l)
{
case English:
db = new english;
langName = "English";
break;
case German:
db = new german;
langName = "German";
break;
}
emit langChanged();
}
the classes german, english are like that
class german : public QList<QObject*>
{
public:
german();
};
german::german()
{
append(new IrregularVerb("anfangen", "fing an", "angefangen"));
/*more like that*/
}
and IrregularVerb:
class IrregularVerb : public QObject
{
Q_OBJECT
Q_PROPERTY(QString form0 READ getForm0 NOTIFY formChanged)
Q_PROPERTY(QString form1 READ getForm1 NOTIFY formChanged)
Q_PROPERTY(QString form2 READ getForm2 NOTIFY formChanged)
public:
QString forms[3];
QString getForm0() const { return getForm(0); }
QString getForm1() const { return getForm(1); }
QString getForm2() const { return getForm(2); }
IrregularVerb(QString a, QString b, QString c) { forms[0] = a; forms[1] = b; forms[2] = c; }
protected:
const QString& getForm(const int& ind) const { return forms[ind]; }
signals:
void formChanged();
};
Edit 2: this doesn't work
If I do
QVariantList getdb() const { return QVariant::fromValue(*db); }
IrregularListWrapper.h:24: error: could not convert 'QVariant::fromValue(const T&) [with T = QList<QObject*>; QVariant = QVariant]()' from 'QVariant' to 'QVariantList {aka QList<QVariant>}'
If I remove the star, the error is similar.
EDIT3:
I found out this http://ruedigergad.com/2011/08/22/qml-sectionscroller-vs-qabstractlistmodel/
And found out that irregulars.db.get is undefined
And changed german and english to
class german : public AbstractIrregularList
and
class AbstractIrregularList : public QObject, public QList<QObject*>
{
Q_OBJECT
public:
Q_INVOKABLE QObject* get(int index) {return at(index);}
};
But even now, irregulars.db.get(0) gives error (Result of expression 'irregulars.db.get' [undefined] is not a function.)
Why is happening like that, that the Q_INVOKABLE is not detected? The Q_OBJECT macro is there
/edit5: Even when using QVariant the errors are still there. It can be either treated as QList or as QObject*.
If I am not wrong, you should use QVariantList instead QList<SomeClass> to expose list of elements from C++ to QML.
It should solve problem.
Supported types in QML
Try making code to look like this (in irregulars header):
Q_PROPERTY(QVariantList db READ getdb NOTIFY langChanged)
//...
QVariantList getdb() const {/*convert db to QVariantList*/ return converted_db;}
Or if you want to code look like from links you gave:
Q_PROPERTY(QVariantList db READ getdb NOTIFY langChanged)
//...
QVariant getdb() const {return QVariant::fromValue(db);}

QT C++ wait till specific time to execute function

I am trying to create an app that holds a list of tasks and for each time a deadline, now i want to execute a function (show a popup) once a deadline is met.
i have this:
#ifndef TIMER_H
#define TIMER_H
#include <QWidget>
#include <QTimer>
#include <QtGui>
#include <QObject>
class Timer : public QWidget
{
Q_OBJECT
public:
Timer(QWidget * parent = 0);
void setTimer(QString title, QString description, QDate date, QTime reminderTime);
public slots:
void showWarning() {QString show = tit;
QPushButton * thanks = new QPushButton(QObject::tr("Thank you for reminding me!"));
show.append("\n");
show.append(des);
QMessageBox popup;
popup.setText(show);
popup.setWindowTitle("Calendar : Reminder");
popup.setDefaultButton(thanks);
popup.exec();
}
private:
QString tit;
QString des;
QDateTime now;
QDateTime timeoftheaction;
QTimer *timer;
};
cpp file:
#endif // TIMER_H
#include "timer.h"
#include <iostream>
using namespace std;
Timer::Timer(QWidget * parent)
: QWidget(parent)
{
}
void Timer::setTimer(QString title, QString description, QDate date, QTime reminderTime)
{
now.currentDateTime();
timer = new QTimer;
tit = title;
des = description;
timeoftheaction.setDate(date);
timeoftheaction.setTime(reminderTime);
connect(timer, SIGNAL(timeout()),this,SLOT(showWarning()));
timer->start(now.secsTo(timeoftheaction)*1000);
}
Yet function showWarning is never being called...
no compilation errors, function showWarning works perfectly (tested)
I think the error is in the connect but i am not sure...
Short answer:
Change:
now.currentDateTime();
to
now = QDateTime::currentDateTime();
Longish answer:
currentDateTime() is a static function which instead of changing your existing object, actually returns a new QDataTime object. Although you are calling it as a member function, it's still called as a static one and leaves your object intact, which is still invalid.
Your later call to secsTo() on an invalid data time probably gets you an negative or really large number that either has passed (never going to trigger) or really late in the future.
Here is something that might be a more generic solution.
#include <QThread>
#include <QTimer>
#include <QObject>
#include <map>
/**
* Singleton to implement simple 'relative' timer.
* Implements busy wait and also timeout-notifications (useful to monitor operations that could hang, etc).
*
* If the whole application is stalled (e.g. when a new device is connected), and we only want to
* wait for a period during which application was 'really' working (not just hanging waiting for OS)
* - then ticks will be missed too. This way - it's should be possible to avoid unnecessary timeouts
* that could happen if global time was measured (especially annoying on WINdows platforms)
*/
class RelativeTimer : public QObject
{
Q_OBJECT
typedef std::multimap <unsigned int, std::pair <QObject*, QString> > Notifications;
public:
/**
* Call to busy-wait for number of ticks.
*/
static void wait_num_of_ticks(unsigned int num_of_ticks_to_wait)
{
if(self.timer_id == 0)
{
qDebug("timer not initialised, call 'RelativeTimer::Init()'");
return;
}
if(num_of_ticks_to_wait > 0)
{
unsigned long until = self.tick_counter + num_of_ticks_to_wait; // it's ok if it wraps around..
while(self.tick_counter != until)
{
QCoreApplication::processEvents(); // let others to their job..
// or comment above out and just busy wait..
}
}
}
/**
* Call to busy-wait until ms_to_wait have elapsed.
* If ms_to_wait is < tick period
* Interval will define 'tick' frequency (and accuracy).
*/
static void wait_ms(unsigned int ms_to_wait)
{
wait_num_of_ticks(num_of_ticks_to_wait(ms_to_wait));
}
/**
* Call to schedule a notification after a given timeout.
* returns notification_id that can be used to cancel this notification.
*/
static unsigned long notify_timeout_ms(unsigned int ms_to_wait,
QObject *receiver,
const char* method_name)
{
unsigned long ticks_to_wait = 0;
if(receiver && method_name)
{
ticks_to_wait = num_of_ticks_to_wait(ms_to_wait);
if(ticks_to_wait > 1)
{
ticks_to_wait += self.tick_counter;
if(ticks_to_wait == 0) // avoid 0 - make it one tick more (to alow to see if successfully added this notif)
{
ticks_to_wait = 1;
}
self.notifications.insert(std::make_pair(ticks_to_wait,
std::make_pair(receiver, method_name)));
qDebug("added delayed call..");
}
else
{
QMetaObject::invokeMethod(receiver, method_name, Qt::QueuedConnection);
ticks_to_wait = 0;
}
}
return ticks_to_wait;
}
/**
* Call to cancel a notification with a given id.
* Specify name if there were more notification with the same id (scheduled for the same tick).
* returns true on successfull cancellation, false otherwise.
*/
static bool cancel_timeout_notification(unsigned long notification_id, QString notification_name="")
{
bool cancelled = false;
if(self.notifications.size())
{
std::pair<Notifications::iterator, Notifications::iterator> to_cancel = self.notifications.equal_range(notification_id);
Notifications::iterator n = to_cancel.first;
for( ;n != to_cancel.second; ++n)
{
if(notification_name.size()== 0 || n->second.second == notification_name)
{
self.notifications.erase(n);
cancelled = true;
break;
}
}
}
return cancelled;
}
static const unsigned int default_tick_period_ms = 100;
/**
* Call this method after event loop is created- to initiate (re-start) timer.
* tick period defines 'tick' frequency (and accuracy of the timer)
* (note on Windows that there's no point to go down below 100ms).
*/
static void Init(unsigned int tick_period_ms = default_tick_period_ms)
{
self.moveToThread(&self.thread);
self.thread.start();
while(!self.thread.isRunning());
self.current_interval = tick_period_ms;
// InitMe() should execute in the thread context..
QMetaObject::invokeMethod(&self, "InitMe", Qt::QueuedConnection);
}
private:
/**
* Internal method to convert ms to number of ticks.
*/
static unsigned int num_of_ticks_to_wait(unsigned int ms_to_wait)
{
if(ms_to_wait > self.current_interval)
{
if(ms_to_wait % self.current_interval)
{
// average it..
ms_to_wait = ms_to_wait + self.current_interval / 2;
}
ms_to_wait /= self.current_interval;
}
else
{
ms_to_wait = 0;
}
return ms_to_wait;
}
/**
* Internal method to handle tick. Increments counter and invokes notifications.
*/
void timerEvent ( QTimerEvent* /*event*/ )
{
tick_counter++;
if(notifications.size())
{
std::pair<Notifications::iterator, Notifications::iterator> to_notify = notifications.equal_range(tick_counter);
Notifications::iterator n = to_notify.first;
for( ;n != to_notify.second; ++n)
{
QMetaObject::invokeMethod(n->second.first,
n->second.second.toStdString().c_str(),
Qt::QueuedConnection);
}
notifications.erase(to_notify.first, to_notify.second);
}
}
private slots:
/**
* Internal slot to initialize the timer. Should be called in this->timer context.
*/
void InitMe()
{
if(timer_id != 0)
{
killTimer(timer_id);
timer_id = 0;
}
tick_counter = 0;
timer_id = self.startTimer(self.current_interval);
}
private:
RelativeTimer()
{
}
~RelativeTimer()
{
thread.quit();
thread.wait();
}
QThread thread;
Notifications notifications;
int timer_id;
unsigned int current_interval;
unsigned long tick_counter;
static RelativeTimer self; // implement it as a signleton.. Define it in your C file, e.g.:
// RelativeTimer RelativeTimer::self;
};
Can be used like:
CurrQObjectClass::OnTimeout()
{
// ...
}
CurrQObjectClass::SomeMethod()
{
RelativeTimer::notify_timeout_ms(5000, this, "OnTimeout");
}
but also for busy-waiting:
RelativeTimer::wait_ms(2000);
Enjoy.

Resources