restrict qualifier on member functions (restrict this pointer)

后端 未结 5 1516
清歌不尽
清歌不尽 2021-01-19 02:13

Note: To clarify, the question is not about the use of the restrict keyword in general, but specifically about applying it to member functions

5条回答
  •  被撕碎了的回忆
    2021-01-19 02:43

    I belive what you guys are missing is that an argument to a member function could also alias parts or an object. Here's an example

    struct some_class {
        int some_value;
    
        void compute_something(int& result) {
            result = 2*some_value;
            ...
            result -= some_value;
        }
    }
    

    One would probably expect that to compile to

    *(this + offsetof(some_value)) -> register1
    2*register1 -> register2
    ...
    register2 - register1 -> result
    

    That code, unfortunately, would be wrong if someone passes a reference to some_value for result. Thus, a compiler would actually need to generate to following

    *(this + offsetof(some_value)) -> register1
    2*register1 -> register2
    register2 -> result
    
    ...
    *(this + offsetof(some_value)) -> register1
    result -> register2
    register2 - register1 -> register2
    register2 -> result
    

    which is obviously way less efficient. Note that unless compute_something is inlines, the compiler has no way of knowing whether result may alias some_value or not, so it has to assume the worst case, no matter no smart or dumb it is. So there a definite and very real advantage to restrict, even if applied to the this pointer.

提交回复
热议问题