尽管获取了错误数据类型的地址,代码仍能编译
#include <iostream>
#define n 255
using namespace std;
int main()
{
int i=n;
int *ptr=&i;
int const *ptr_1=&i;
const int *ptr_2=&i;
const int * const ptr_3=&i;
}
为什么此代码可以在 Visual C++、Dev C++ 和 G++ 中编译? 链接到 - Ideone -
#include <iostream>
#define n 255
using namespace std;
int main()
{
int i=n;
int *ptr=&i;
int const *ptr_1=&i;
const int *ptr_2=&i;
const int * const ptr_3=&i;
}
Why does this Code Compile in Visual C++, Dev C++ and G++?
Link to - Ideone -
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
它确实可以编译,因为所有这些指针都不会更改变量访问的 const 限定或强制限定,但它们都不会尝试放松限定。
例如:
尝试对 const 变量进行非常量访问,这是非法的,但
尝试对非常量变量进行常量访问,这是合法的,因为非常量变量确实允许仅 const 访问。
It does compile, because all those pointers ether don't change
const
-qualification of the variable access or enforce the qualification, but none of them tries to loosen the qualification.For example:
would try to get non-const access to a const variable and that's illegal, but
tries to get const access to a non-const variable and that's legal since a non-const variable does allow const-only access.
因为没有什么问题吗?
两边的类型相同:
int *ptr=&i;
更多 const,完全没问题:
int const *ptr_1=&i;
与上面的行完全相同:
const int *ptr_2=&i;
更多 const,完全没问题:
const int * const ptr_3=&i;
你总是可以创建一个变量 more< /strong> 常量。
上面的内容使 j less const 并且无效。
4.4/1:(涵盖
int *
到int const *
)Because there's nothing wrong with it?
Same types on both side:
int *ptr=&i;
More const, perfectly ok:
int const *ptr_1=&i;
Exactly the same as above line:
const int *ptr_2=&i;
More const, perfectly ok:
const int * const ptr_3=&i;
You can always make a variable more const.
The above makes j less const and isn't valid.
4.4/1: (Covers
int *
toint const *
)您可能想知道为什么在获取地址时可以将值设置为 const。
这是合法的,在 C++ 术语中称为
const
提升。请注意,仅一个级别的
const
提升可能会发生 - 也就是说,int**
可能会提升为int * const*
但不是int const**
(const
必须向左“移动”两个位置)。You are probably wondering why the value can be made
const
when taking the address.This is legal and is known as
const
promotion in C++ parlance.Note that only one level of
const
promotion may happen – that is, aint**
may be promoted toint* const*
but not toint const**
(theconst
would have to “move” two places to the left).C++ 允许您创建指向在堆栈上创建的变量的指针。因此,这段代码没有任何问题。而且,它经常被用来向WINAPI等函数传递参数。
如果问题是关于指针的语义,那么答案是成熟的。
例如:
只要记住 * 之前的修饰符指的是变量,后面的修饰符 - 指的是指针。
C++ allows you to create pointers to the variables created on the stack. Thus, there is nothing wrong with this code. Moreover, it is often used to pass parameters to functions such as WINAPI.
If the question about the semantics of pointers then the answer is a full-fledged.
For example:
Just remember that the modifiers before * refer to the variable, after it - to the pointer.