简体   繁体   中英

Why do I get this warning on MSVC?

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

Now the warning I get is:

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

However since the return type of std::map s count() method is:

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

Hence it can be used pretty much like a boolean. So why exactly do I get this warning? In C++ integers can basically be used for boolean checks right? Hence 0 == false and 1 == true . So why does the compiler throw me a warning? I also tried using a static_cast like this:

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

but I'm still getting the warning.

In general, an unsigned int is not a bool , hence the warning. Try:

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

instead.

size_type count ( const key_type& x ) const;

A prvalue of arithmetic, unscoped enumeration, pointer, or pointer to member type can be converted to a prvalue of type bool. A zero value, null pointer value, or null member pointer value is converted to false; any other value is converted to true. A prvalue of type std::nullptr_t can be converted to a prvalue of type bool; the resulting value is false.

By standard program is well-formed and should works on all compilers, that support standard.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM