RAM有效的C ++属性

属性是类的公共数据成员,可以由客户端代码访问。每当客户端代码读取或修改属性时,所有者对象都会收到一条通知(以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))。

或者也许还有另一种方法?

ABC402543999 回答:RAM有效的C ++属性

c ++具有语言扩展属性

msvc has support

clang编译器也支持此语法。我不确定gcc

也可以存储偏移量

只需在构造函数中计算距this的偏移量即可。 :

Prop( Super& super ) {
  uint8_t offset = this - std::addressof(super );//somewhat unmaintable - but may save some bytes
}

然后在使用时,使用this

计算

请注意,由于对齐和填充,节省的空间可能少于看起来的空间。

,

我显然不知道您的代码的上下文,因此在您的特定实现中这是不可想象的,但是您可以执行类似的操作

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;
}

很显然,您需要初始化向量并处理错误情况等,但是逻辑就在那里-如果您仅通过prop访问super

这使您仅具有结构序列的大小,而没有指向super的指针。

本文链接:https://www.f2er.com/3124071.html

大家都在问