为什么 "The 'empty' method should be used to check for emptiness instead of 'size" by clang-tidy?

Why "The 'empty' method should be used to check for emptiness instead of 'size" by clang-tidy?

执行检查时:

std::string st = "hello";
bool is_empty = st.size() > 0;

我收到上面提到的 Clang-Tidy 警告。

为什么改用 empty() 方法更好?

根据Clang documentation

readability-container-size-empty

Checks whether a call to the size() method can be replaced with a call to empty().

The emptiness of a container should be checked using the empty() method instead of the size() method. It is not guaranteed that size() is a constant-time function, and it is generally more efficient and also shows clearer intent to use empty(). Furthermore some containers may implement the empty() method but not implement the size() method. Using empty() whenever possible makes it easier to switch to another container in the future.

std::forward_list 是没有 size() 方法的容器的示例,如下所示:

根据 isocpp

的标准,size() 的 C++11 时间复杂度为 常数