Why does constructing std::string(0) not emit a compiler warning?

你离开我真会死。 提交于 2019-12-12 14:23:13

问题


Say I have this piece of code.

#include <string>

int main()
{
    std::string(0);
    return 0;
}

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.

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".


回答1:


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




回答2:


Because those compilers seem to miss this feature. I recommend to write them a featurereport.

A compiler can easily regognize the std string class internally and emit a sensible warning.

I don't know why you want to restrict the warning only to the cast-free cases though. Having a cast there or otherwise passing a null pointer is equally nonsensible.



来源:https://stackoverflow.com/questions/13394212/why-does-constructing-stdstring0-not-emit-a-compiler-warning

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!