[英]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__
成員函數限定符的解釋與const
或volatile
限定符的解釋不同,因為它應用於指針而不是對象。 這與實現受限指針的其他編譯器一致。
但請注意, this
指針標記為不會阻止第二次加載。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.