operator new overloading and alignment

前端 未结 2 616
情深已故
情深已故 2020-12-12 21:08

I\'m overloading operator new, but I recently hit a problem with alignment. Basically, I have a class IBase which provides operator new

2条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-12 21:19

    mixins are the right approach, however overloading operator new is not. This will accomplish what you need:

    __declspec(align(256))  struct cachealign{};
    __declspec(align(4096)) struct pagealign{};
    struct DefaultAlign{};
    struct CacheAlign:private cachealign{};
    struct PageAlign: CacheAlign,private pagealign{};
    
    void foo(){
     DefaultAlign d;
     CacheAlign c;
     PageAlign p;
     std::cout<<"Alignment of d "<<__alignof(d)<

    Prints

    Alignment of d 1
    Alignment of c 256
    Alignment of p 4096
    

    For gcc, use

    struct cachealign{}__attribute__ ((aligned (256)));
    

    Note that there is automatic selection of the largest alignment, and this works for objects placed on the stack, ones that are new'd, and as members of other classes. Nor does it add any virtuals and assuming EBCO, no extra size to the class (outside of the padding needed for the alignment itself).

提交回复
热议问题