[英]How does compiler treat a const function?
I understand that a function is considered to be constant (bitwise constness) by compiler and if any statement brings modification in the state of object then compiler would throw an error as in Example 1. 我了解编译器将函数视为常量(按位常量),如果任何语句对对象状态进行了修改,则编译器将像示例1一样抛出错误。
Example 1: 范例1:
class Test
{
public:
int arr[5];
void change(int j) const
{
arr[3]=j;
}
};
int main()
{
Test *ptr=new Test;
ptr->change(3);
}
Example2 : Now I have declared arr
as an array a pointer, but the following seems to have been working on a few compilers — but on mine it doesn't. 例2:现在我已经将
arr
声明为一个指针数组 ,但是以下内容似乎已经在一些编译器上工作了,但是在我看来却没有。 Does it mean it has UB? 这是否意味着它有UB? One of the legitimate explanations I came across mentions that we are not directly changing the object hence this is allowed.
我遇到的一种合理解释提到我们不是直接更改对象,因此可以这样做。 If so then why UB in my case?
如果是这样,那我为什么要UB? I'm using VS2008.
我正在使用VS2008。
class Test
{
public:
int *arr; //arr is an array
int i;
void change(int j) const
{
arr[3]=j;
}
};
int main()
{
Test *ptr=new Test;
ptr->change(3);
}
First, int *ptr
does not declare ptr
as an array. 首先,
int *ptr
不会将ptr
声明为数组。 ptr
is a pointer here. ptr
是这里的指针 。
Second, the reason your code exhibits undefined behaviour is that you're using an uninitialized pointer. 其次,您的代码表现出未定义行为的原因是您使用的是未初始化的指针。
ptr->change(3)
effectively does ptr->arr[3] = 3;
ptr->change(3)
有效地执行ptr->arr[3] = 3;
. 。 But you don't know what
ptr->arr
points to, so you don't know where you're writing the number 3 to. 但是您不知道
ptr->arr
指向什么,所以您不知道将数字3写入到哪里。 Maybe it'll point at some unused memory that's safe to overwrite, maybe it'll point to unallocated memory and crash your program as soon as you try to access it, or maybe it'll overwrite something important. 也许它将指向一些可以安全覆盖的未使用的内存,也许它将指向未分配的内存并在您尝试访问它时使程序崩溃,或者可能会覆盖一些重要的信息。
Separately: the reason it compiles is that while arr
is part of the class Test
, *arr
isn't. 另外: 编译的原因是,虽然
arr
是Test
类的一部分,但*arr
不是。 From inside change
, you can't alter arr
, but you can alter *arr
. 从内部
change
,您不能更改arr
,但是可以更改*arr
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.