Write-Only pointer type

前端 未结 6 850
执念已碎
执念已碎 2021-01-30 16:14

I\'m writing software for an embedded system.

We are using pointers to access registers of an FPGA device.
Some of the registers are read-only, while others are wr

6条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-30 16:54

    I'd probably write a tiny wrapper class for each:

    template 
    class read_only {
        T volatile *addr;
    public:
        read_only(int address) : addr((T *)address) {}
        operator T() volatile const { return *addr; }
    };
    
    template 
    class write_only { 
        T volatile *addr;
    public:
        write_only(int address) : addr ((T *)address) {}
    
        // chaining not allowed since it's write only.
        void operator=(T const &t) volatile { *addr = t; } 
    };
    

    At least assuming your system has a reasonable compiler, I'd expect both of these to be optimized so the generated code was indistinguishable from using a raw pointer. Usage:

    read_only x(0x1234);
    write_only y(0x1235);
    
    y = x + 1;         // No problem
    
    x = y;             // won't compile
    

提交回复
热议问题