簡體   English   中英

如何在此指針上應用restrict限定符

[英]How to apply restrict qualifier on this pointer

如何將GCC的/ Clang的__restrict__限定符應用於類的this指針?
這個問題的靈感來自Richard Powell的CppCon 2018演講,“ How to Argue(ment)。 ”我看到了類似的問題“ 限制成員函數的限定符(限制此指針)。 ”(所有代碼都可以在Compiler Explorer上找到)

void bar();

class Foo {
 public:
  int this_example() const {
    if (value > 0) {
      bar();
      return value;
    } else {
      return value;
    }
  }

 private:
  int value;
};

上面的代碼生成以下程序集。 在其中,我們可以看到value必須通過this指針加載兩次。 這是有道理的,這是C ++繼承自C和限制限定符允許程序員關閉行為的結果。 我找不到為this指針啟用restrict功能的方法。

Foo::this_example() const:               # @Foo::this_example() const
        push    rbx
        mov     eax, dword ptr [rdi]
        test    eax, eax
        jle     .LBB2_2
        mov     rbx, rdi
        call    bar()
        mov     eax, dword ptr [rbx]
.LBB2_2:
        pop     rbx
        ret

Compiler Explorer頁面上,我展示了使用__restrict__來消除第二次加載的方法參數的示例。 還有一個將struct引用傳遞給函數並使用__restrict__來消除第二個加載的示例。

我可以想象一個編譯器允許程序員在方法的參數中提到隱式this指針的世界。 然后,編譯器可以允許將限定符應用於this指針。 請參閱下面的代碼示例。

class Foo {
 public:
  int unrestricted(Foo *this);
  int restricted(Foo *__restrict__ this);
};

作為后續行動的問題,是有什么在C ++標准或C ++指南,將讓這個this可能永遠不會有限制預選賽?

GCC的__restrict__文檔 (以及鏈接的問題)提到你實際上可以限制this

您還可以使用__restrict__作為成員函數限定符來指定成員函數的this指針是否為unaliased。

 void T::fn () __restrict__ { /* … */ } 

T::fn的主體內, this具有有效的定義T *__restrict__ const this 請注意, __restrict__成員函數限定符的解釋與constvolatile限定符的解釋不同,因為它應用於指針而不是對象。 這與實現受限指針的其他編譯器一致。

但請注意, this指針標記為不會阻止第二次加載。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM