c++ - 为什么我会在 MSVC 上收到此警告?

标签 c++ visual-c++ boolean warnings compiler-warnings

bool image_manager::contains_image(const std::string& filename)
{
    return this->map_.count(filename);
}

现在我得到的警告是:

warning C4800: 'unsigned int' : forcing value to bool 'true' or 'false' (performance warning)

但是由于 std::map 的 count() 方法的返回类型是:

1 if an element with a key equivalent to x is found, or zero otherwise.

因此它可以像 boolean 值一样使用。那么为什么我会收到这个警告呢?在 C++ 中,整数基本上可以用于 boolean 检查,对吧?因此 0 == false1 == true。那么为什么编译器会给我一个警告呢?我也试过像这样使用 static_cast:

return static_cast<bool>(this->map_.count(filename));

但我仍然收到警告。

最佳答案

一般来说,unsigned int 不是 bool,因此会出现警告。尝试:

return this->map_.count(filename) > 0;

相反。

关于c++ - 为什么我会在 MSVC 上收到此警告?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11702824/

相关文章:

c++ - 从另一个类调用构造函数

c++ - 优先函数

visual-c++ - 为什么VC2012编译器会进入stackoverflow(错误C1063)?

c++ - 如何将项目 win32 控制台应用程序转换为 C++ Windows 窗体?

javascript - boolean 问题

java - 以下代码的 && 语句和嵌套条件是否等价?

c++ - lambda 表达式的可变参数模板

c++ - _CrtSetAllocHook - 未处理的异常

boolean - jq-如何选择字段为 'false'的对象?

c++ - ICU 无法解析的外部符号