Does `const T *restrict` guarantee the object pointed-to isn’t modified?

后端 未结 4 1295
南笙
南笙 2020-12-16 19:32

Consider the following code:

void doesnt_modify(const int *);

int foo(int *n) {
    *n = 42;
    doesnt_modify(n);
    return *n;
}

where

4条回答
  •  甜味超标
    2020-12-16 20:04

    If not, is there a (portable, if possible) way to tell the compiler doesnt_modify doesn’t modify what its argument points to?

    No such way.

    Compiler optimizers have difficulty optimizing when pointer and reference function parameters are involved. Because the implementation of that function can cast away constness compilers assume that T const* is as bad as T*.

    Hence, in your example, after the call doesnt_modify(n) it must reload *n from memory.

    See 2013 Keynote: Chandler Carruth: Optimizing the Emergent Structures of C++. It applies to C as well.

    Adding restrict keyword here does not change the above.

提交回复
热议问题