[c++专家答]C++作为C语言的超级语言 需要 restrict 关键字吗?
答案:1 悬赏:40
解决时间 2021-02-10 14:27
- 提问者网友:伪善人独行者
- 2021-02-09 15:10
[c++专家答]C++作为C语言的超级语言 需要 restrict 关键字吗?
最佳答案
- 二级知识专家网友:佛说妍妍很渣
- 2021-02-09 16:14
现在的C++编译器,无论是GCC,Clang,VC++,IBM XL C++等,这些主流的C++编译器都提供了restrict关键字的支持,只是似乎书写的形式有所变化,如可能是__restrict__,__restrict等 ,而restrict是限制Pointer Alias的,这和unique_ptr完全是两码事,限制Pointer Alias有助于编译器做优化。至于为什么C++标准委员会不加,我现在也不知道,我也感觉很诧异,不过下次我会记得问导师Michael,但是可能要等到8月份了,我现在手上也有一大堆的C++问题等着问他,包括Module System是否在C++17挂掉了等,因为我上次看见有人在我的评论说这个挂了,我比较疑惑。
然后补充一下restrict的用法,我以GCC产生汇编指令的例子来补充一下,比较直观
void f(int *a, int *b, int *c)
{
*a += *c;
*b += *c;
}-O3后的汇编代码
f(int*, int*, int*):
movl (%rdx), %eax
addl %eax, (%rdi)
movl (%rdx), %eax
addl %eax, (%rsi)
ret加上restrict
void f(int * __restrict__ a, int* __restrict__ b, int* __restrict__ c)
{
*a += *c;
*b += *c;
}-O3后
f(int*, int*, int*):
movl (%rdx), %eax
addl %eax, (%rdi)
addl %eax, (%rsi)
ret
可以很清楚的看见是4条指令变为了3条指令,而少掉的一条就是第二次的load c
然后看看unique_ptr
#include
using namespace std;
void f(std::unique_ptr a, std::unique_ptrb, std::unique_ptr c)
{
*a += *c;
*b += *c;
}-O3 -std=c++11
f(std::unique_ptr >, std::unique_ptr >, std::unique_ptr >):
movq (%rdx), %rdx
movq (%rdi), %rax
; *a += *c
movl (%rdx), %ecx
addl %ecx, (%rax)
movq (%rsi), %rax
; *b += *c
movl (%rdx), %edx
addl %edx, (%rax)
ret所以,可见,unique_ptr和restrict完全是两码事。
然后补充一下restrict的用法,我以GCC产生汇编指令的例子来补充一下,比较直观
void f(int *a, int *b, int *c)
{
*a += *c;
*b += *c;
}-O3后的汇编代码
f(int*, int*, int*):
movl (%rdx), %eax
addl %eax, (%rdi)
movl (%rdx), %eax
addl %eax, (%rsi)
ret加上restrict
void f(int * __restrict__ a, int* __restrict__ b, int* __restrict__ c)
{
*a += *c;
*b += *c;
}-O3后
f(int*, int*, int*):
movl (%rdx), %eax
addl %eax, (%rdi)
addl %eax, (%rsi)
ret
可以很清楚的看见是4条指令变为了3条指令,而少掉的一条就是第二次的load c
然后看看unique_ptr
#include
using namespace std;
void f(std::unique_ptr
{
*a += *c;
*b += *c;
}-O3 -std=c++11
f(std::unique_ptr
movq (%rdx), %rdx
movq (%rdi), %rax
; *a += *c
movl (%rdx), %ecx
addl %ecx, (%rax)
movq (%rsi), %rax
; *b += *c
movl (%rdx), %edx
addl %edx, (%rax)
ret所以,可见,unique_ptr和restrict完全是两码事。
我要举报
如以上问答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
推荐资讯
• 手机登qq时,显示手机磁盘不足,清理后重新登 |
• 刺客的套装怎么选啊? |