Here is the typical (pseudo) code I wish to handle in clang-tidy (eg also here) for conveying an optionally null terminated fixed size buffer to std::string
:
% cat str.cc
#include <iostream>
#include <string>
// read byte buffer from file, at most 4 bytes read:
static void read_buf4(char buf[4])
{
buf[0] = 'A';
buf[1] = 'B';
buf[2] = 'C';
// buf[3] = 'D';
buf[3] = 0;
}
int main()
{
char buf[4];
read_buf4(buf);
std::string owner = std::string(buf,sizeof buf).c_str();
// I want owner.size() to return strnlen(buf,4):
std::cout << owner << "/" << owner.size() << std::endl;
return 0;
}
What would be the most acceptable solution to help clang-tidy understand the code ?
Currently reporting:
% clang-tidy --checks="-*,readability-redundant-string-cstr" str.cc
Error while trying to load a compilation database:
Could not auto-detect compilation database for file "str.cc"
No compilation database found in /tmp or any parent directory
fixed-compilation-database: Error while opening fixed database: No such file or directory
json-compilation-database: Error while opening JSON database: No such file or directory
Running without flags.
1 warning generated.
/tmp/str.cc:17:23: warning: redundant call to 'c_str' [readability-redundant-string-cstr]
std::string owner = std::string(buf,sizeof buf).c_str();
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
std::string(buf,sizeof buf)