c++:有没有办法确保编译器调用两次相同的 const 方法得到相同的结果?
c++: is there a way to ensure the compiler that calling twice the same const method gives the same result?
我对以下 2 个简单的片段感到困惑:
#include <vector>
struct A{
int foo(int i) const {return v[i];}
std::vector<int> v;
};
int f(const A &a, int i) {
int j;
j=a.foo(i);
j=a.foo(i);
return j;
}
其中给出了汇编代码:
movsxd rax, esi
mov rcx, qword ptr [rdi]
mov eax, dword ptr [rcx + 4*rax]
ret
和
#include <vector>
struct A{
int foo(int i) const;
std::vector<int> v;
};
int f(const A &a, int i) {
int j;
j=a.foo(i);
j=a.foo(i);
return j;
}
给出:
push rbp
push rbx
push rax
mov ebp, esi
mov rbx, rdi
call _ZNK1A3fooEi
mov rdi, rbx
mov esi, ebp
add rsp, 8
pop rbx
pop rbp
jmp _ZNK1A3fooEi # TAILCALL
在第一种情况下,编译器'sees' 函数的内部foo
并得到他不必调用它两次。在第二种情况下,它只有它的声明,似乎不能假设它只能调用一次函数,而函数是const...这是为什么呢?这是 i
和函数内部 foo
之间的别名问题吗?如果这是一个别名问题,我如何确保编译器不担心这个问题?
成员函数是 const
限定的事实并不意味着该函数没有任何副作用。在没有看到函数定义的情况下,编译器无法确定该函数不会将某些内容输出到文件中,不会通过网络发送某些内容等。因此,通常,仅调用一次相同的成员函数可能不会产生等效的结果调用它两次(尽管函数是 const
限定的)。
编辑:回答最初的问题:目前,没有标准的方法来将函数标记为没有副作用。一些编译器可能支持自定义属性,例如 [[gnu::pure]]
和 [[gnu::const]]
,但这不是标准的。
我对以下 2 个简单的片段感到困惑:
#include <vector>
struct A{
int foo(int i) const {return v[i];}
std::vector<int> v;
};
int f(const A &a, int i) {
int j;
j=a.foo(i);
j=a.foo(i);
return j;
}
其中给出了汇编代码:
movsxd rax, esi
mov rcx, qword ptr [rdi]
mov eax, dword ptr [rcx + 4*rax]
ret
和
#include <vector>
struct A{
int foo(int i) const;
std::vector<int> v;
};
int f(const A &a, int i) {
int j;
j=a.foo(i);
j=a.foo(i);
return j;
}
给出:
push rbp
push rbx
push rax
mov ebp, esi
mov rbx, rdi
call _ZNK1A3fooEi
mov rdi, rbx
mov esi, ebp
add rsp, 8
pop rbx
pop rbp
jmp _ZNK1A3fooEi # TAILCALL
在第一种情况下,编译器'sees' 函数的内部foo
并得到他不必调用它两次。在第二种情况下,它只有它的声明,似乎不能假设它只能调用一次函数,而函数是const...这是为什么呢?这是 i
和函数内部 foo
之间的别名问题吗?如果这是一个别名问题,我如何确保编译器不担心这个问题?
成员函数是 const
限定的事实并不意味着该函数没有任何副作用。在没有看到函数定义的情况下,编译器无法确定该函数不会将某些内容输出到文件中,不会通过网络发送某些内容等。因此,通常,仅调用一次相同的成员函数可能不会产生等效的结果调用它两次(尽管函数是 const
限定的)。
编辑:回答最初的问题:目前,没有标准的方法来将函数标记为没有副作用。一些编译器可能支持自定义属性,例如 [[gnu::pure]]
和 [[gnu::const]]
,但这不是标准的。