C ++ 11向后兼容性(将空整数常量转换为指针) [英] C++11 backwards compatibility (conversion of null integer constant to pointer)
问题描述
C ++标准允许将零整数常量隐式转换为任何类型的指针。
The C++ standard allows the implicit conversion of zero integer constant to pointer of any type.
以下代码无效,值 v 在此不是常数:
The following code is invalid, because the value v
is not constant here:
float* foo()
{
int v = 0;
return v; // Error
}
但以下代码是正确的:
float* foo()
{
const int v = 0;
return v; // Ok in C++98 mode, error in C++11 mode
}
问题是:为什么 gcc
和 clang
正确地在c ++ 98/03模式,但在c ++ 11/14模式下编译时返回警告/错误( -std = c ++ 11
)?我尝试在C ++ 11工作草稿PDF中找到更改,但没有成功。
The question is: why gcc
and clang
(tried different versions) compile the code correctly in c++98/03 mode but return warning/error when compiled in c++11/14 mode (-std=c++11
)? I tried to find the changes in C++11 working draft PDF, but got no success.
Intel编译器16.0和VS2015编译器在这两种情况下都不显示错误和警告。
Intel compiler 16.0 and VS2015 compilers show no errors and warnings in both cases.
推荐答案
GCC和Clang的行为不同于 -std = c ++ 11
因为C ++ 11改变了空指针常量的定义,然后C ++ 14再次改变它,参见Core DR 903 更改了C ++ 14中的规则,因此只有文字是空指针常量。
GCC and Clang behave differently with -std=c++11
because C++11 changed the definition of a null pointer constant, and then C++14 changed it again, see Core DR 903 which changed the rules in C++14 so that only literals are null pointer constants.
在C ++ 03 4.10 [conv.ptr]说:
In C++03 4.10 [conv.ptr] said:
一个空指针常量是一个整数常数表达式
A null pointer constant is an integral constant expression (5.19) rvalue of integer type that evaluates to zero.
允许所有类型的表达式,只要它们是常量并且计算结果为零。枚举, false
,(5 - 5)
等等...这个会导致很多问题C ++ 03代码。
That allows all sorts of of expressions, as long as they are constant and evaluate to zero. Enumerations, false
, (5 - 5)
etc. etc. ... this used to cause lots of problems in C++03 code.
在C ++ 11中,它表示:
In C++11 it says:
空指针常量是整数类型的整数常数表达式(5.19),其值为零或
std :: nullptr_t
类型的prvalue
A null pointer constant is an integral constant expression (5.19) prvalue of integer type that evaluates to zero or a prvalue of type
std::nullptr_t
.
在C ++ 14中,它说:
And in C++14 it says:
指针常数是值为零的整数字符(2.14.2)或类型
std :: nullptr_t
的prvalue。
这是一个更加严格的规则,更有意义。
This is a much more restrictive rule, and makes far more sense.
这篇关于C ++ 11向后兼容性(将空整数常量转换为指针)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!