ericniebler / range-v3

Range library for C++14/17/20, basis for C++20's std::ranges
Other
4.06k stars 437 forks source link

view::join providing different results with const char* vs std::string #1699

Open caloudes opened 2 years ago

caloudes commented 2 years ago

When providing a const char * into join, it is considering the null terminator to be something to be included in the join.

Sample reproduction code:

std::vector<std::string> numbers = {"one", "two", "three"};

auto cStrJoinedNumbers = numbers | view::join(", ") | to<std::string>();
std::cout << cStrJoinedNumbers << std::endl;
std::cout << folly::hexDump(cStrJoinedNumbers.c_str(), cStrJoinedNumbers.size())
          << std::endl;

auto stdStrJoinedNumbers =
    numbers | view::join(std::string{", "}) | to<std::string>();
std::cout << stdStrJoinedNumbers << std::endl;
std::cout << folly::hexDump(
                 stdStrJoinedNumbers.c_str(),
                 stdStrJoinedNumbers.size())
          << std::endl;

Output:

one, two, three
00000000  6f 6e 65 2c 20 00 74 77  6f 2c 20 00 74 68 72 65  |one, .two, .thre|
00000010  65                                                |e               |

one, two, three
00000000  6f 6e 65 2c 20 74 77 6f  2c 20 74 68 72 65 65     |one, two, three |
dvirtz commented 2 years ago

It's a general "problem" with string literals. You should use views::c_str to ignore the null terminator. https://gcc.godbolt.org/z/4z7e858v8