为什么构造std :: string(0)不会发出编译器警告? [英] Why does constructing std::string(0) not emit a compiler warning?
问题描述
说我有这段代码。
#include <string>
int main()
{
std::string(0);
return 0;
}
写 std :: string(0)
会导致调用 std :: basic_string< char> :: basic_string(const char *)
,其中 0
作为此构造函数的参数,它将尝试将该参数视为指向C字符串的指针。
Writing std::string(0)
results in std::basic_string<char>::basic_string(const char*)
being called, with 0
as the argument to this constructor, which tries to treat the argument as a pointer to a C-string.
运行此代码显然会导致 std :: logic_error
被抛出。但是我的问题是:为什么GCC和MSVC 8.0都不会发出任何警告?我希望能看到从没有转换的整数中获取指针的思路。
Running this code obviously results in a std::logic_error
being thrown. But my question is this : why both GCC and MSVC 8.0 don't emit any warnings? I'd expect to see something along the lines of "Making pointer from an integer without a cast".
推荐答案
0
是一个整数常量表达式,其值为0,因此它是一个空指针常量。将值0的常量用作空指针不是强制转换。
0
is an integer constant expression with value 0, so it is a null pointer constant. Using a 0-valued constant as a null pointer is not a cast.
C ++ 11引入了 nullptr
(和 nullptr_t
),但是 0
作为空指针的处理在不久的将来不太可能改变代码取决于它。
C++11 introduces nullptr
(and nullptr_t
), but the treatment of 0
as a null pointer is unlikely to change in the near future as large amounts of code depends on it.
这篇关于为什么构造std :: string(0)不会发出编译器警告?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!