ReadabilityRedundantStringInit when assigning an empty string to std::string_view Follow V Created September 20, 2022 10:01 This initialization would be redundant in std::string case, but as you can see std::string_view is different.
Sorry about the late reply.
As the documentation (https://clang.llvm.org/extra/clang-tidy/checks/readability/redundant-string-init.html) for this check mentions, initializing a string_view with an empty string literal produces an instance that compares equal to string_view(). This means there's usually no reason to initialize a string_view with an empty string literal.
There is. string_view() produces an instance that is effectively uninitialized. Instance produced by string_view(""), on the other hand, is in valid state and perfectly usable.
Implementation of the equality operator for this particular class is questionable and so is your argument.
Imagine replacing every empty string literal occurrence in your codebase with nullptr. Or vice-versa – nullptr with "". The one reviewing such changes could ever approve them only after getting hit by a truck. Twice in a row.
If you don't agree with the motivation for this check, simply disable it. It's as simple as that.
This check is alright, but only when it's applied to owning strings. In non-owning strings case the equality check terminates when size() is zero, it doesn't care whether either of operands contain null pointer.
"View on nothing" versus "view on an empty string":
*std::string_view().data() -> segfault; *std:: string_view("").data() -> '\0'. And occurrence of '\0' is a loop exit condition for many algorithms.
I propose to at least separate this check for owning and non-owning strings.