尽管采用了错误数据类型的地址,代码仍会编译

时间:2011-03-14 14:40:00

标签: c++ const

#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 -

4 个答案:

答案 0 :(得分:7)

它确实编译,因为所有这些指针都不会改变const - 变量访问的限定或强制执行资格,但是没有一个试图放松资格。

例如:

const int var;
int* address = &var; //illegal - tries to remove const

会尝试获取const变量的非const访问权限,这是非法的,但是

int var;
const int* address = &var; //legal - only adds const

尝试获取对非const变量的const访问权,这是合法的,因为非const变量允许const-only访问。

答案 1 :(得分:3)

因为它没有任何问题吗?

两边的相同类型:int *ptr=&i;

更多常量,完全可以:int const *ptr_1=&i;

与上述行完全相同:const int *ptr_2=&i;

更多常量,完全可以:const int * const ptr_3=&i;

您始终可以创建一个变量 more const。

int const * i;
int * j = i;

以上使j less const并且无效。

4.4 / 1 :(涵盖int *int const *

  

“指向cv1 T的指针”类型的右值   可以转换为类型的右值   如果“cv2 T”更多,则指向“cv2 T”   cv-qualified比“cv1 T。”

答案 2 :(得分:0)

您可能想知道为什么在获取地址时可以使const值。

这是合法的,在C ++用语中被称为 const promotion

请注意,只有{em>一级的const促销可能会发生 - 也就是说,int**可能会提升为int* const*但不会提升为int const**const必须向左移动两个地方。

答案 3 :(得分:0)

C ++允许您创建指向堆栈上创建的变量的指针。因此,这段代码没有任何问题。此外,它通常用于将参数传递给WINAPI等函数。

如果关于指针语义的问题那么答案是完全成熟的。 例如:

int * ptr; //pointer to a variable. Pointer and the variable can be changed.
int const * ptr; //a pointer to the constant variable, a pointer can be changed, the variable can not.
const int * ptr; //same as above.
const int * const ptr_3; //the most interesting section, a const pointer to const variable. 

请记住*之前的修饰符引用变量,在它之后 - 指向指针。