属性是类的公共数据成员,可以由客户端代码访问。每当客户端代码读取或修改属性时,所有者对象都会收到一条通知(以get / set通知回调的形式)。
某些语言(例如C#)具有内置属性。
我想为C ++创建一个将提高RAM效率的属性。
制作属性的最明显方法是这样的:
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; }
问题是-每个属性都必须保留指向我认为代价高昂的外部类的指针。
我想知道是否有更有效的RAM方式来做到这一点?
例如,如果生成了所有Super
类,那么标准是否允许从属性的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;
};
由于此偏移量是一个常数表达式,因此(理论上)它可以保存在ROM中(或者至少可以小于sizeof(pointer))。
或者也许还有另一种方法?