Stop Code instead of break with a Error Message - c++

Here is some code that is from a great website which does what i want quite well (searching in a vector of class objects by addressing the class objects).
#include <iostream>
#include <vector>
#include <functional>
#include <algorithm>
using namespacestd;
class class1
{
private:
int id;
double value;
public:
class1(int i, double v) :id(i), value(v){ }
int getId()const { return id; }
double getValue() const { return value; }
};
class HasIdentifier :public unary_function<class1, bool>
{
public:
HasIdentifier(int id) : m_id(id) { }
bool operator()(const class1& c)const
{
return (c.getId() == m_id);
}
private:
int m_id;
};
class class2
{
private:
vector <class1> objects;
public:
class2()
{
objects.push_back(class1(1, 100.0));
objects.push_back(class1(2, 100.0));
objects.push_back(class1(3, 100.0));
}
double GetValueOfId(int id)
{
vector<class1>::iterator itElem = find_if(objects.begin(), objects.end(), HasIdentifier(id));
return itElem->getValue();
}
};
int main() {
class2 c;
int id = 4;
cout << id << " " << c.GetValueOfId(id);
cin.get();
return 0;
}
It works well but whenenver i put "int id ">3 it crashes because object only has the size 3. I got this, but is there a possibility to get warned when this will happen so that is does not crash but im able to correct it somehow in the code with a warn message?

You should check the returned iterator for validness and throw and exception (or report an error any other way) if it is invalid:
if (itElem == objects.end())
throw MyVeryCoolException("Woops wrong id");
Dont forget to set up a global exception handler (toplevel catch), otherwise your application will still crash if the exception is uncaught.

Related

Access violation exeption in c++

I'm trying to learn c++, I've read a lot about it and get it, but every time I program something that uses OOP concepts I have memory problems.
This is the exeption I'm getting with my code:
First-chance exception at 0x002EFB60 in Mathmatician.exe: 0xC0000005: Access violation executing location 0x002EFB60.
If there is a handler for this exception, the program may be safely continued.
So my question here is:
what is wrong with my specific code?
And more importantly, how can I avoid such exeptions? Are ther rules of thumb in c++ to avoid these?
And another thing: How can I avoid returning a local variable from a function that gets deleted (I assume just return the value itself, not a pointer?)
(More info:This specific code will be used to calculate derivative, with diffrent formulas like devision, multiplication, and more inhereting from the Form virtual class)
// Mathmatician.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <typeinfo>
#include <iostream>
using namespace std;
#include <sstream>
template <typename T>
std::string NumberToString ( T Number )
{
std::ostringstream ss;
ss << Number;
return ss.str();
}
class Form {
public:
virtual Form& Derive() = 0;
Form& operator+(Form& const other);
Form& operator*(Form& const other);
virtual string Print() = 0;
};
class Number : public Form {
public:
int a;
Number(int a) : a(a)
{}
Form& Derive()
{
return (Form&) Number(0);
}
string Print()
{
return NumberToString(a);
}
};
class Addition : public Form {
private:
Form& a;
Form& b;
public:
Addition(Form& const a, Form& const b) : a(a),b(b)
{
}
Form& Derive()
{
return a.Derive() + b.Derive();
}
string Print()
{
return "("+a.Print();// + "+" + b.Print()+")";
};
};
class Multiply : public Form {
private:
Form& a;
Form& b;
public:
Multiply(Form& a, Form& b) : a(a),b(b)
{
}
Form& Derive()
{
return *new Addition(a.Derive(),b.Derive());
//return a.Derive()*b + b.Derive()*a;
}
string Print()
{
return "("+a.Print() + "*" + b.Print()+")";
};
};
inline Form& Form::operator+(Form& const other) // copy assignment
{
return Addition(*this,other);
//LocationNode* A = new LocationNode('A',1,2);
}
inline Form& Form::operator*(Form& const other) // copy assignment
{
return Multiply(*this,other);
}
int _tmain(int argc, _TCHAR* argv[])
{
Form* n = &(*new Addition((Form&)*new Number(5),(Form&)*new Number(5))).Derive();
cout << (*n).Derive().Print() << "/n";
return 0;
}
Thank you!
You may see my answer here. The problem of new is that it does not clear the memory of the allocated space. The solution for new is to add the following line as long as you initialized the elements.
memset(element,0,sizeof(element));
Therefore you can ensure there is no garbage in the memory.
This answer is somehow based on my C language experience. Recently I found that C++ has another function called std::fill
using namespace std;
/* some function */
fill(elem,elem+sizeof(elem),0);
/* end of some funtion */

Get derived class with base class function

I need to do some equality checks with different types on a class hierarchy. In pseudo code:
#include <string>
#include <memory>
#include <iostream>
using namespace std;
class ComplexType {};
class Property {};
class IntegerProperty : public Property {
public:
int inner;
};
class StringProperty : public Property {
public:
string inner;
};
class ComplexTypeProperty : public Property {
ComplexType inner;
};
int main() {
shared_ptr<Property> p1 = getSomewhere(); //this is in fact a pointer on IntegerProperty
shared_ptr<Property> p2 = getSomewhere(); // this is in fact a pointer on StringProperty
shared_ptr<Property> p3 = getSomewhere(); // this is in fact a pointer on CompleyTypeProperty
ComplexType c;
cout << ((*p1) == 2);
cout << ((*p2) == "foo");
cout << ((*p3) == c);
}
It it simple to provide a operator== for the derived classes, but I cannot cast before checking, because the type of p1 and p2 is not clear at compile time.
Another way I know is to write the operator== function in the Property base class and throw some exceptions if the type is wrong, but I want, that the Property class can be subclassed later without changing the code for Property and it will work, too.
Templating Property is also not (directly) possible, because e.g. in my code a vector<shared_ptr<Property>> has to exist.
Is there some (generic) way to implement main() to get the equality checks, so that later subclassing of Property without changing the class itself is possible?
Have found some way of solving this. I'm not quite happy with the code. So if anyone has a better solution, please provide it.
#include <string>
#include <memory>
#include <iostream>
using namespace std;
class ComplexType {
public:
bool operator==(const ComplexType& i) {
return true;
}
};
inline ostream& operator<<(ostream& os, const ComplexType& c) {
os << "ComplexType";
return os;
}
class Property {
public:
virtual ~Property() {}
};
template <class T>
class LayerProperty : public Property {
private:
T inner;
public:
LayerProperty(T t) : inner(t) {}
bool operator==(const T i) {
return inner == i;
}
};
int main() {
shared_ptr<Property> p1 = make_shared<LayerProperty<int>>(LayerProperty<int>(5));
shared_ptr<Property> p2 = make_shared<LayerProperty<string>>(LayerProperty<string>("foo"));
shared_ptr<Property> p3 = make_shared<LayerProperty<ComplexType>>(LayerProperty<ComplexType>(ComplexType()));
ComplexType c;
cout << ((*dynamic_pointer_cast<LayerProperty<decltype(2)>>(p1)) == 2) << "\n";
// special case std::string
auto a = "foo";
auto s = "";
if (typeid(a) == typeid(s)) {
cout << ((*dynamic_pointer_cast<LayerProperty<decltype(string(a))>>(p2)) == a) << "\n";
}
cout << ((*dynamic_pointer_cast<LayerProperty<decltype(c)>>(p3)) == c) << "\n";
return 0;
}

Iterate through a list of types

How can I iterate through a list of types without creating an instance of each type?
In my example, I have a parent class with a method, getByName which returns an instance of a child class. The getByName method is entirely broken since you cannot create an array of typedefs. What is the best way to make this work?
One solution is to create an array of name pointers, but this would get messy if there are multiple variables (more than just name) that I want to check against.
I basically want a clean solution that uses a loop rather than a series of if statements.
#include <string>
struct Number {
Number(const std::string &name) :name(name) {}
// fix me!
static Number* getByName(const std::string &name) {
typedef types[] = {
One,
Two,
Three,
}
for (int i = 0; i < 3; ++i) {
if (name == types[i]::name)
return new types[i]();
}
return nullptr;
}
const std::string name;
};
struct One :Number {
One() :Number(name) {}
const static std::string name;
};
struct Two :Number {
Two() :Number(name) {}
const static std::string name;
};
struct Three :Number {
Three() :Number(name) {}
const static std::string name;
};
const std::string One::name = "one";
const std::string Two::name = "two";
const std::string Three::name = "three";
You may implement your factory as follow
template <typename T>
static std::pair<std::string, std::function<Number*()>> register_helper()
{
return { T::name, []() { return new T{}; }};
}
static Number* getByName(const std::string &name) {
static const std::map<std::string, std::function<Number*()>> factories = {
register_helper<One>(),
register_helper<Two>(),
register_helper<Three>()
};
auto it = factories.find(name);
if (it == factories.end()) {
return nullptr;
} else {
return it->second();
}
}
Live Demo
You can't store types directly in a meaningful fashion; however, you can store pointers to factory functions, which should be equally useful:
#include <iostream>
#include <string>
#include <map>
using namespace std;
struct Number;
Number* oneCreator();
Number* twoCreator();
Number* threeCreator();
struct Number {
typedef Number* (*creatorFP)();
typedef map<string, creatorFP> CreatorMap;
static Number* getByName(const string &name) {
// maybe initialise this map somewhere else
CreatorMap creators;
creators.insert(make_pair(string("one"), &oneCreator));
creators.insert(make_pair(string("two"), &twoCreator));
creators.insert(make_pair(string("three"), &threeCreator));
CreatorMap::iterator creator = creators.find(name);
if (creator != creators.end()) {
return (*(creator->second))();
}
return NULL;
}
virtual void f() { cout << "NUMBER" << endl; }
};
struct One : Number {
virtual void f() { cout << "ONE" << endl; }
};
struct Two : Number {
virtual void f() { cout << "TWO" << endl; }
};
struct Three : Number {
virtual void f() { cout << "THREE" << endl; }
};
Number* oneCreator() { return new One(); }
Number* twoCreator() { return new Two(); }
Number* threeCreator() { return new Three(); }
int main() {
Number *two = Number::getByName(string("two"));
two->f();
return 0;
}
Trying for something a little simpler then previous pitches, and assuming that getByName isn't called with an unsupported value all that often.
template <typename TYPE>
Number * factory()
{
return new TYPE();
}
static const std::map<std::string, Number*(*)()> factories =
{
{One::name, factory<One>},
{Two::name, factory<Two>},
{Three::name, factory<Three>}
};
static Number* getByName(const std::string &name)
{
try
{
return factories.at(name)();
}
catch (std::out_of_range &e)
{
// Log factory called with bad name as a hint that the programmer
// should check calling code.
return nullptr;
}
}
But if calls with bad names are an expected use case, the hard way is much less expensive than handling the exception.
static Number* getByName(const std::string &name)
{
auto factory = factories.find(name);
if (factory != factories.end())
{
return factory->second();
}
return nullptr;
}

"no matching function" initializing class

I got that message
no matching function for call to 'main()::MySeqInFileEnumerator::MySeqInFileEnumerator(const char [10])'
when im doing my string matching job.I have to method override existing code.I have to open an input text, and make an abstract file from it, then i have to do an optimistic linsearch.
#include <iostream>
#include "linsearch.hpp"
#include "seqinfileenumerator.hpp"
using namespace std;
struct MyPair
{
int azon;
int osszeg;
friend ifstream& operator>>(ifstream& f, MyPair& df);
};
ifstream& operator>>(ifstream& f, MyPair& df)
{
f >> df.azon >> df.osszeg;
return f;
}`enter code here`
int main()
{
class MyLinSearch: public LinSearch <int, true>
{
bool Cond(const int& e) const
{
return e<=-100000;
}
};
class MySeqInFileEnumerator: public SeqInFileEnumerator <MyPair>
{
void Next()
{
MyPair dx;
f >> dx;
df.azon=dx.azon;
df.osszeg=dx.osszeg;
while(dx.azon==df.azon)
{
dx.osszeg+=df.osszeg;
f >> dx;
}
}
};
MyLinSearch pr;
MySeqInFileEnumerator t("input.txt");
pr.AddEnumerator(&t);
pr.Run();
if (pr.Found())
{
cout << "false " << endl;
}
else cout << "true" << endl;
return 0;
}
As the error message says, the class has no constructor taking a string; yet you try to use one with
MySeqInFileEnumerator t("input.txt");
Perhaps the base class has a suitable constructor? In that case, you'll need to forward the argument:
explicit MySeqInFileEnumerator(char const * name) :
SeqInFileEnumerator<MyPair>(name)
{}
You forgot to add a suitable constructor. Something like this:
class MySeqInFileEnumerator: public SeqInFileEnumerator<MyPair>
{
public:
MySeqInFileEnumerator(char const * p) : SeqInFileEnumerator<MyPair>(p) { }
// ...
};
(This is assuming your base class has a corresponding constructor. Modify to taste.

Property like features in C++?

My use is pretty complicated. I have a bunch of objs and they are all passed around by ptr (not reference or value unless its an enum which is byval). At a specific point in time i like to call CheckMembers() which will check if each member has been set or is null. By default i cant make it all null because i wouldnt know if i set it to null or if it is still null bc i havent touch it since the ctor.
To assign a variable i still need the syntax to be the normal var = p; var->member = new Type;. I generate all the classes/members. So my question is how can i implement a property like feature where i can detect if the value has been set or left as the default?
I am thinking maybe i can use C++ with CLR/.NET http://msdn.microsoft.com/en-us/library/z974bes2.aspx but i never used it before and have no idea how well it will work and what might break in my C++ prj (it uses rtti, templates, etc).
Reality (edit): this proved to be tricky, but the following code should handle your requirements. It uses a simple counter in the base class. The counter is incremented once for every property you wish to track, and then decremented once for every property that is set. The checkMembers() function only has to verify that the counter is equal to zero. As a bonus, you could potentially report how many members were not initialized.
#include <iostream>
using namespace std;
class PropertyBase
{
public:
int * counter;
bool is_set;
};
template <typename T>
class Property : public PropertyBase
{
public:
T* ptr;
T* operator=(T* src)
{
ptr = src;
if (!is_set) { (*counter)--; is_set = true; }
return ptr;
}
T* operator->() { return ptr; }
~Property() { delete ptr; }
};
class Base
{
private:
int counter;
protected:
void TrackProperty(PropertyBase& p)
{
p.counter = &counter;
counter++;
}
public:
bool checkMembers() { return (counter == 0); }
};
class OtherObject : public Base { }; // just as an example
class MyObject : public Base
{
public:
Property<OtherObject> x;
Property<OtherObject> y;
MyObject();
};
MyObject::MyObject()
{
TrackProperty(x);
TrackProperty(y);
}
int main(int argc, char * argv[])
{
MyObject * object1 = new MyObject();
MyObject * object2 = new MyObject();
object1->x = new OtherObject();
object1->y = new OtherObject();
cout << object1->checkMembers() << endl; // true
cout << object2->checkMembers() << endl; // false
delete object1;
delete object2;
return 0;
}
There are a number of ways to do this, with varying tradeoffs in terms of space overhead. For example, here's one option:
#include <iostream>
template<typename T, typename OuterClass>
class Property
{
public:
typedef void (OuterClass::*setter)(const T &value);
typedef T &value_type;
typedef const T &const_type;
private:
setter set_;
T &ref_;
OuterClass *parent_;
public:
operator value_type() { return ref_; }
operator const_type() const { return ref_; }
Property<T, OuterClass> &operator=(const T &value)
{
(parent_->*set_)(value);
return *this;
}
Property(T &ref, OuterClass *parent, setter setfunc)
: set_(setfunc), ref_(ref), parent_(parent)
{ }
};
struct demo {
private:
int val_p;
void set_val(const int &newval) {
std::cout << "New value: " << newval << std::endl;
val_p = newval;
}
public:
Property<int, demo> val;
demo()
: val(val_p, this, &demo::set_val)
{ }
};
int main() {
demo d;
d.val = 42;
std::cout << "Value is: " << d.val << std::endl;
return 0;
}
It's possible to get less overhead (this has up to 4 * sizeof(void*) bytes overhead) using template accessors - here's another example:
#include <iostream>
template<typename T, typename ParentType, typename AccessTraits>
class Property
{
private:
ParentType *get_parent()
{
return (ParentType *)((char *)this - AccessTraits::get_offset());
}
public:
operator T &() { return AccessTraits::get(get_parent()); }
operator T() { return AccessTraits::get(get_parent()); }
operator const T &() { return AccessTraits::get(get_parent()); }
Property &operator =(const T &value) {
AccessTraits::set(get_parent(), value);
return *this;
}
};
#define DECL_PROPERTY(ClassName, ValueType, MemberName, TraitsName) \
struct MemberName##__Detail : public TraitsName { \
static ptrdiff_t get_offset() { return offsetof(ClassName, MemberName); }; \
}; \
Property<ValueType, ClassName, MemberName##__Detail> MemberName;
struct demo {
private:
int val_;
struct AccessTraits {
static int get(demo *parent) {
return parent->val_;
}
static void set(demo *parent, int newval) {
std::cout << "New value: " << newval << std::endl;
parent->val_ = newval;
}
};
public:
DECL_PROPERTY(demo, int, val, AccessTraits)
demo()
{ val_ = 0; }
};
int main() {
demo d;
d.val = 42;
std::cout << "Value is: " << (int)d.val << std::endl;
return 0;
}
This only consumes one byte for the property struct itself; however, it relies on unportable offsetof() behavior (you're not technically allowed to use it on non-POD structures). For a more portable approach, you could stash just the this pointer of the parent class in a member variable.
Note that both classes are just barely enough to demonstrate the technique - you'll want to overload operator* and operator->, etc, as well.
Here's my temporary alternative. One that doesn't ask for constructor parameters.
#include <iostream>
#include <cassert>
using namespace std;
template <class T>
class Property
{
bool isSet;
T v;
Property(Property&p) { }
public:
Property() { isSet=0; }
T operator=(T src) { v = src; isSet = 1; return v; }
operator T() const { assert(isSet); return v; }
bool is_set() { return isSet; }
};
class SomeType {};
enum SomeType2 { none, a, b};
class MyObject
{
public:
Property<SomeType*> x;
Property<SomeType2> y;
//This should be generated. //Consider generating ((T)x)->checkMembers() when type is a pointer
bool checkMembers() { return x.is_set() && y.is_set(); }
};
int main(int argc, char * argv[])
{
MyObject* p = new MyObject();
p->x = new SomeType;
cout << p->checkMembers() << endl; // false
p->y = a;
cout << p->checkMembers() << endl; // true
delete p->x;
delete p;
}