class item
{
int i;
public:
item(int no) {
}
};
I want to check the constructor parameter. If it is found to hold a negative value, then object creation should be stopped.
Exceptions can not be used here as the targeted system does not support exceptions.
There is no way to stop the creation of an object without throwing. The best you can do is set an "invalid parameter" flag that you have to check afterwards, and if true discard the object without using it.
With the requirements you have, it would probably be better to use a factory method to create the objects -- this way, you can make the checks before calling the constructor:
class item
{
int i;
public:
static item* create(int no) {
if (no < 0) {
return 0;
}
return new item(no);
}
private:
item(int no) {
}
};
You could use this like
item* myItem = item::create(-5);
if(!myItem) {
// failed
}
However, this forces you to allocate all item instances on the heap.
Exceptions are the way designated by the standard to perform this task; there's no other way to abort completely the object creation.
On the other hand, you can give your class some "state" member that specifies that the class was not correctly constructed and check it at every method call (a bit like how iostream classes work).
class item
{
int i;
bool validState;
public:
item(int no) : validState(true)
{
if(/* no is invalid */)
{
validState = false;
return;
}
/* ... */
}
bool ValidState() { return validState; }
SomeType DoSomething()
{
if(!ValidState())
{
// do nothing/report the error to the caller
}
// ...
}
}
IMO it's cumbersome, but if you don't have exceptions and want to create objects via a public constructor there's nothing much better than this.
You cannot stop object construction mid-way, without throwing an exception.
That said, you may outright prevent construction of item objects which fail a precondition, by moving the precondition and object-creation responsibilities to a separate factory function, and making the constructors private (to disallow all other ways to construct the object):
class item {
int i;
public:
static item* create( int no )
{
return no < 0 ? NULL : new item( no );
}
private:
item() { ... }
item( int no ) { ... }
};
Three options.
Use a flag in your class to track full construction - but you'll have to test that in each method.
Make item a wrapper, such that the internals are held in a class that is constructed if the arguments are good, but in all the methods, you'll have to test the internals - so no different to 1 anyway.
Use a factory to return a smart pointer if the arguments are good.
My preference in this scenario is the last one.
Put the object into an error state (use a boolean) and then all methods should return an error.
ie
class Item
{
int i;
bool errorState;
public:
Item(int n) : i(n) {
errorState = i < 0;
}
bool method()
{
if (errorState) return false;
..... do stuff here
return true;
}
}
You can do it at compile time with necessary warning flags ON (e.g. -Wall in gcc).
class item
{
public:
item(unsigned int no) {} // item takes only +ve value
};
Compiler will warn you if a -ve value is passed.
Related
A property is a public data member of a class, which can be accessed by client code. And the owning object receives a notification (in the form of get/set notification callback) whenever the client code reads or modifies the property.
Some languages (like C#) have built-in properties.
I want to create a property for C++ that will be RAM-efficient.
The most obvious way to make a property is something like this:
class Super;
struct Prop {
Prop( Super * super ) : m_super(*super), m_a(0) {}
int operator=( int a );
operator int() const;
int m_a;
Super & m_super;
};
struct Super {
Super() : one(this), two(this) {}
void onSet() { printf("set"); }
void onGet() { printf("get"); }
Prop one;
Prop two;
};
int Prop::operator=( int a ) { m_super.onSet(); m_a = a; return a; }
Prop::operator int() const { m_super.onGet(); return m_a; }
Trouble is - every property has to keep a pointer to the outer class which I consider costly.
I want to know if there is a more RAM-efficient way to do this?
For example, if all Super-classes are generated, is it allowed by the Standard to get a pointer to the outer class from this pointer of the property?
Something like this:
struct Prop {
Prop( uint8_t offset ) : m_offset(offset), m_a(0) {}
int operator=( int a );
operator int() const;
int m_a;
const uint8_t m_offset;
};
int Prop::operator=( int a ) {
Super * super = (Super *)( ((char *)this) + m_offset);
super->onSet(); m_a = a; return a;
}
struct Super {
// assuming exact order of properties
Super() : one(0), two(sizeof(Prop)) {}
void onSet() { printf("set"); }
void onGet() { printf("get"); }
Prop one;
Prop two;
};
Since this offset is a constant expression it (theoretically) can be kept in ROM (or at least it can be smaller than sizeof(pointer)).
Or maybe there is another way?
c++ has properties as language extension
Look no further, msvc has support.
clang compiler also supports this syntax. Im not sure about gcc.
Storing offset can be also be done
Just, in the constructor calculate the offset from this, ala. :
Prop( Super& super ) {
uint8_t offset = this - std::addressof(super );//somewhat unmaintable - but may save some bytes
}
then when used, calculate back using this
Please note the space saving may be less than it seems due to alignment and padding.
I obviously don't know the context of your code, so this may be inconceivable in your specific implementation, but you could do something like
class Prop(){
Prop() : m_a(0){};
int operator=(int a){m_a = a;};
int m_a;
}
class Super(){
public:
int set_prop(int index, int value){
m_props[index] = value;
onSet();
return value;
}
private:
void onSet(){};
std::vector<Prop> m_props;
}
Obviously you need to initialize the vector and handle error cases etc but the logic is there - if you only access the props through the super.
That leaves you with purely the size of the sequence of structs with no pointers back to the super.
I have code like this:
class Human
{
protected:
int age;
std::string sex;
public:
virtual void speak() = 0;
};
class Child:public Human
{
public:
void speak(){std::cout << "I am Child\n";}
};
class Man:public Human
{
public:
void speak(){std::cout << "I am Man\n";}
};
class Woman:public Human
{
public:
void speak(){std::cout << "I am Woman\n";}
};
(don't know, std::shared_ptr<Human> maybe?) operator*(std::shared_ptr<Child> &b, int x)
{
b->setAge(b->getAge()+x);
if(b->getAge()>18 && b->getSex()=="Man")
{
return (i want b to become std::shared_ptr<Man>)
}
if(b->getAge()>18 && b->getSex()=="Woman")
{
return (here I want b to become std::shared_ptr<Woman>);
}
return;
}
int main(){
auto x = std::make_shared<Child>;
x*19;
}
I know it seems odd, but it's the simplest case i can think of, without having to write down all code i'm struggling with rn. Could someone explain, what type should overload be and how to change shared_ptr type, knowing they derive from same parent?
Objects cannot change type. A Child object will always be a Child object. What you can do is create a new object with the properties you want and return that:
std::shared_ptr<Human> operator*(std::shared_ptr<Human> b, int x)
{
b->setAge(b->getAge()+x);
if(b->getAge()>18 && b->getSex()=="Man") {
return std::make_shared<Man>(b->getAge());
} else if(b->getAge()>18 && b->getSex()=="Woman") {
return std::make_shared<Woman>(b->getAge());
} else {
return b;
}
}
int main(){
std::shared_ptr<Human> x = std::make_shared<Child>;
x = x*19;
}
This doesn't seem like a good design though. A Human's status as a child or adult would be better represented as an attribute of the object or by a function that checks if age is greater than 18.
You cannot make the type T<Derived> inherit from T<Base> because C++ templates do not support covariance. To do so would be unsafe for certain types, such as mutable references to containers. (Imagine taking a reference to std::vector<Cat> as std::vector<Animal>& and pushing back a dog!)
(I would make this answer a comment, but I don't have comment abilities.)
Update:
You can write a non-template wrapper that handles heap data:
class Wrapper
{
public:
Wrapper(Base* b) : raw(b) {}
~Wrapper() { delete raw; }
Base& get() { return *base; }
private:
Base* raw;
}
Of course, in your example, you use std::shared_ptr and not std::unique_ptr. You would have to handle reference counting instead of simply deleting the data in the destructor, but the technique of keeping an internal raw pointer still stands.
Update 2:
The above code could be used as is to provide a level of indirection, such that all classes that inherit from the base class may be held in the same type, without writing your own reference counter:
std::shared_ptr<Wrapper>
This solution may be seen as similar to doing std::shared_ptr<Base*>, except that the latter solution would leak memory.
I have a class transition and inside, a member function rate. I am asking for a method that would allow me to insert custom designed rates into instants of transition, after those instants have been created, and would be fast at run-time!
I would like to optimize the code for speed. rate does simple computations but is called very frequently and many times by the program. So I guess I should avoid virtual functions... Question: what are the other best methods to achieve this in C++ (templates,boost,...)? Comments about the speed of a particular method would be appreciated. Thanks!
class transition {
public:
transition() : vec() {}
double rate(T_vec::iterator a) { return ...; }
private:
T_vec vec;
};
/* custom rate #1 */
double my_rate_1( T_vec::iterator) {
/* do something */
return ans;
}
/* custom rate #2 */
double my_rate_2( T_vec::iterator) {
/* do something */
return ans;
}
const int N=10;
int main (void) {
vector<transition*> ts(N);
for(int i=0;i!=N;++i) ts[i] = new transition;
/* How to efficiently implement the pseudo code that follows? */
ts[0]->rate = my_rate_1;
ts[1]->rate = my_rate_2;
/* ... */
}
There are at least three ways to implement this.
Option 1 is virtual methods. You can't bind the method after you create the instance, but after the creation you can treat all the derived classes as transition.
class transition {
...
virtual double rate(T_vec::iterator a) = 0;
};
class my_transition_1 : public transition {
...
double rate(T_vec::iterator a) { ... }
};
class my_transition_2 : public transition {
...
double rate(T_vec::iterator a) { ... }
};
Option 2 is callbacks. You can change the method at runtime, after you created the object. It's the most dynamic. It has slightly higher overhead in this case, because there is an extra copy construction of the iterator, and it is harder for the compiler to optimize away the indirect call.
class transition {
public:
....
typedef double (*RateFunction)(T_vec::iterator a);
void set_rate(RateFunction r) { _fun = r; }
double rate(T_vec::iterator a) { return (*_fun)(a); }
private:
RateFunction _fun;
};
double my_rate_1(T_vec::iterator a) {
...
}
...
transition t;
t.set_rate(my_rate_1);
Option 3 is functor templates. You have to specify everything at construction time, but this avoids the indirect call and has the best performance.
template <typename Rate>
class transition {
double rate(T_vec::iterator a) {
return Rate()(a);
}
};
class my_rate_1 {
double operator()(T_vec::iterator a) {
....
}
};
class my_rate_2 {
double operator()(T_vec::iterator a) {
....
}
};
transition<my_rate_1> t1;
transition<my_rate_2> t2;
Option 4 is not extensible, but you avoid the indirect function call and have the opportunity to set the rate after creating the object.
class transition {
public:
enum RateCode {
RATE_1,
RATE_2,
...
}
double rate(T_vec::iterator i) {
switch (_rate_code) {
case RATE_1: {
...
return result;
}
case RATE_2: {
...
return result;
}
default:
assert(false);
}
}
void setRate(RateCode r) { _rate_code = r; }
private:
RateCode _rate_code;
}
If you want to bind to arbitrary functions, check the FastDelegate article. There is also an article of a more portable implementation of the delegate idea.
If you can arrange your code such that the specific instance is known at compile time, this will be faster, assuming the compiler does its job well. The reason why it is faster is that a true delegate implies a call to a function pointer, and that breaks the speculative execution and pipelining in today's CPU's.
You might also want to read up on C++11. In C++11, lambda functions (inline written functions that can be passed around) are an important extension, and I would expect compilers to work hard to optimize them.
I am working on design a wrapper class to provide RAII function.
The original use case is as follows:
void* tid(NULL);
OpenFunc(&tid);
CloseFunc(&tid);
After I introduce a new wrapper class, I expect the future usage will be as follows:
void* tid(NULL);
TTTA(tid);
or
TTTB(tid);
Question:
Which implementation TTTA or TTTB is better? Or they are all bad and please introduce a better one.
One thing I have concern is that after the resource is allocated, the id will be accessed outside of class TTTA or TTTB until the id is destroyed. Based on my understanding, my design should not have side-effect for that.
Thank you
class TTTA : boost::noncopyable
{
public:
explicit TTTA(void *id)
: m_id(id)
{
OpenFunc(&m_id); // third-party allocate resource API
}
~TTTA()
{
CloseFunc(&m_id); // third-party release resource API
}
private:
void* &m_id; // have to store the value in order to release in destructor
}
class TTTB : boost::noncopyable
{
public:
explicit TTTB(void *id)
: m_id(&id)
{
OpenFunc(m_id); // third-party allocate resource API
}
~TTTB()
{
CloseFunc(m_id); // third-party release resource API
}
private:
void** m_id; // have to store the value in order to release in destructor
}
// pass-in pointers comparison
class TTTD
{
public:
TTTD(int* id) // Take as reference, do not copy to stack.
: m_id(&id)
{
*m_id = new int(40);
}
private:
int** m_id;
};
class TTTC
{
public:
TTTC(int* &id)
: m_id(id)
{
m_id = new int(30);
}
private:
int* &m_id;
};
class TTTB
{
public:
TTTB(int* id)
: m_id(id)
{
m_id = new int(20);
}
private:
int* &m_id;
};
class TTTA
{
public:
TTTA(int** id)
: m_id(id)
{
*m_id = new int(10);
}
private:
int** m_id;
};
int main()
{
//////////////////////////////////////////////////////////////////////////
int *pA(NULL);
TTTA a(&pA);
cout << *pA << endl; // 10
//////////////////////////////////////////////////////////////////////////
int *pB(NULL);
TTTB b(pB);
//cout << *pB << endl; // wrong
//////////////////////////////////////////////////////////////////////////
int *pC(NULL);
TTTC c(pC);
cout << *pC << endl; // 30
//////////////////////////////////////////////////////////////////////////
int *pD(NULL);
TTTD d(pD);
cout << *pD << endl; // wrong
}
Both break in bad ways.
TTTA stores a reference to a variable (the parameter id) that's stored on the stack.
TTTB stores a pointer to a variable that's stored on the stack.
Both times, the variable goes out of scope when the constructor returns.
EDIT: Since you want the values modifiable, the simplest fix is to take the pointer as a reference; that will make TTTC reference the actual pointer instead of the local copy made when taking the pointer as a non reference parameter;
class TTTC : boost::noncopyable
{
public:
explicit TTTA(void *&id) // Take as reference, do not copy to stack.
: m_id(id)
...
private:
void* &m_id; // have to store the value in order to release in destructor
}
The simple test that breaks your versions is to add a print method to the classes to print the pointer value and do;
int main() {
void* a = (void*)0x200;
void* b = (void*)0x300;
{
TTTA ta(a);
TTTA tb(b);
ta.print();
tb.print();
}
}
Both TTTA and TTTB print both values as 0x300 on my machine. Of course, the result is really UB; so your result may vary.
Why do you tid at all? It’s leaking information to the client and makes the usage twice as long (two lines instead of one):
class tttc {
void* id;
public:
tttc() {
OpenFunc(&id);
}
~tttc() {
CloseFunc(&id);
}
tttc(tttc const&) = delete;
tttc& operator =(tttc const&) = delete;
};
Note that this class forbids copying – your solutions break the rule of three.
If you require access to id from the outside, provide a conversion inside tttc:
void* get() const { return id; }
Or, if absolutely necessary, via an implicit conversion:
operator void*() const { return id; }
(But use that one judiciously since implicit conversions weaken the type system and may lead to hard to diagnose bugs.)
And then there’s std::unique_ptr in the standard library which, with a custom deleter, actually achieves the same and additionally implements the rule of three properly.
What about wrapping it completely? This way you do not have to worry about managing the lifecycles of two variables, but only one.
class TTTC
{
void* m_id;
public:
TTTC()
: m_id(nullptr)
{
OpenFunc(&m_id); // third-party allocate resource API
}
TTTC(TTTC const&) = delete; // or ensure copying does what you expect
void*const& tid() const { return m_id; }
~TTTC()
{
CloseFunc(&m_id); // third-party release resource API
}
};
Using it is simplicity itself:
TTTC wrapped;
DoSomethingWithTid(wrapped.tid());
How to Define or Implement C# Property in ISO C++ ?
Assume following C# code :
int _id;
int ID
{
get { return _id; }
set { _id = value; }
}
I know C# convert the get and set lines to getXXX and setXXX methods in compile time. in C++ , programmers usually define these two function manually like :
int _id;
int getID() { return _id; }
void setID(int newID) { _id = newID; }
but, I want to have the C# syntax or a stuff like it in order to have a simple usability.
In C#, we can use properties like :
ID = 10; // calling set function
int CurrentID = ID; // calling get function
In C++, we can use our function like :
setID(10); // calling set function
int CurrentID = getID(); // calling get function
Now tell me how can I implement the C# properties in ISO C++.
thanks.
As Alexandre C. has already stated, it's very awkward and not really worth it, but to give an example of how you might do it.
template <typename TClass, typename TProperty>
class Property
{
private:
void (TClass::*m_fp_set)(TProperty value);
TProperty (TClass::*m_fp_get)();
TClass * m_class;
inline TProperty Get(void)
{
return (m_class->*m_fp_get)();
}
inline void Set(TProperty value)
{
(m_class->*m_fp_set)(value);
}
public:
Property()
{
m_class = NULL;
m_fp_set = NULL;
m_fp_set = NULL;
}
void Init(TClass* p_class, TProperty (TClass::*p_fp_get)(void), void (TClass::*p_fp_set)(TProperty))
{
m_class = p_class;
m_fp_set = p_fp_set;
m_fp_get = p_fp_get;
}
inline operator TProperty(void)
{
return this->Get();
}
inline TProperty operator=(TProperty value)
{
this->Set(value);
}
};
In your class where you wish to use it, you create a new field for the property, and you must call Init to pass your get/set methods to the property. (pref in .ctor).
class MyClass {
private:
int _id;
int getID() { return _id; }
void setID(int newID) { _id = newID; }
public:
Property<MyClass, int> Id;
MyClass() {
Id.Init(this, &MyClass::getID, &MyClass::setID);
}
};
Short answer: you can't.
Long answer: You could try to simulate them via proxy classes, but believe me this is not worth the minor incovenience in having set/get functions.
You'd have basically to define a class which forwards all the behavior of the variable. This is insanely hard to get right, and impossible to be made generic.
Quite simply. I'd argue this even has no overhead compared to making the variable public. However, you can't modify this any further. Unless, of course, you add two more template parameters that are call backs to functions to call when getting and setting.
template<typename TNDataType>
class CProperty
{
public:
typedef TNDataType TDDataType;
private:
TDDataType m_Value;
public:
inline TDDataType& operator=(const TDDataType& Value)
{
m_Value = Value;
return *this;
}
inline operator TDDataType&()
{
return m_Value;
}
};
EDIT: Don't make the call back functions template parameters, just data members that are constant and must be initialized in the constructor for the property. This inherently has greater overhead than simply writing a get and set method your self, because you're making function calls inside of your gets and sets this way. The callbacks will be set at run-time, not compile-time.