117

Using http://en.cppreference.com/w/cpp/string/basic_string_view as a reference, I see no way to do this more elegantly:

std::string s = "hello world!";
std::string_view v = s;
v = v.substr(6, 5); // "world"

Worse, the naive approach is a pitfall and leaves v a dangling reference to a temporary:

std::string s = "hello world!";
std::string_view v(s.substr(6, 5)); // OOPS!

I seem to remember something like there might be an addition to the standard library to return a substring as a view:

auto v(s.substr_view(6, 5));

I can think of the following workarounds:

std::string_view(s).substr(6, 5);
std::string_view(s.data()+6, 5);
// or even "worse":
std::string_view(s).remove_prefix(6).remove_suffix(1);

Frankly, I don't think any of these are very nice. Right now the best thing I can think of is using aliases to simply make things less verbose.

using sv = std::string_view;
sv(s).substr(6, 5);
10
  • 6
    "I don't think any of these are very nice" What is wrong with the first one? Seems completely clear to me. Edit: BTW combining two methods that have clear meaning individually (string_view(s).substr(...)) seems nicer than a single function doing two things at once (.substr_view(...)) even if it did exist. Sep 4, 2017 at 9:20
  • 2
    @sehe: are you suggesting that std::string::substr should return a std::string_view?
    – geza
    Sep 4, 2017 at 9:33
  • 1
    @geza I strongly seem to remember additions to std::basic_string<> interface that would add an operation like subtr_view, indeed. I mentioned that in the question. I was hoping someone would respond and say "That's proposal Nxxxx which got rejected/accepted into C++zz or TSn"
    – sehe
    Sep 4, 2017 at 9:40
  • 1
    @ArthurTacca since the operation is so common, I think there should be a 1 step operation, possibly also more efficient. And certainly less error-prone: coliru.stacked-crooked.com/a/fd180519dc9b2f00 A free function is now the best we can do (in absense of en.wikipedia.org/wiki/Uniform_Function_Call_Syntax)
    – sehe
    Sep 4, 2017 at 9:44
  • 5
    @sehe so the upshot of my alarmist ranting in the cpporg group is that no-one else seems to think that string_view is a problem. The answer seems to be, "just never return a string_view", adding string_view to the arbitrary list of classes that one should "just know" not to return. In which case the std::string_view::substr() method breaks its own rules, since it returns a string_view. So I guess the advice would be never to do this. Use a std::string. Sep 5, 2017 at 7:56

4 Answers 4

63

You can use the conversion operator from std::string to std::string_view:

std::string s = "hello world!";
std::string_view v = std::string_view(s).substr(6, 5);
8
  • This approach is not obviously efficient (i.e. does it do the job without allocating an extra temporary buffers?), so a comment supporting the claim to efficiency would be good. In fact, it looks like this approach is very contra-indicated because v points at a temporary buffer that immediately becomes invalid. Jul 26, 2020 at 23:03
  • 1
    @JohnDoggett: What are you talking about? Why should there be a temporary buffer?
    – MikeMB
    Jan 3, 2021 at 9:53
  • 6
    Imho this is a far better solution than the accepted one.
    – MikeMB
    Jan 3, 2021 at 9:54
  • 4
    @caps no, string_view::substr returns a view based on the original view. Perhaps it would have been less confusing if they'd called it subview?
    – M.M
    Jan 27, 2021 at 9:53
  • 1
    @M.M you are correct. I thought the code sample was calling string::substr.
    – caps
    Feb 3, 2021 at 21:36
61

There's the free-function route, but unless you also provide overloads for std::string it's a snake-pit.

#include <string>
#include <string_view>

std::string_view sub_string(
  std::string_view s, 
  std::size_t p, 
  std::size_t n = std::string_view::npos)
{
  return s.substr(p, n);
}

int main()
{
  using namespace std::literals;

  auto source = "foobar"s;

  // this is fine and elegant...
  auto bar = sub_string(source, 3);

  // but uh-oh...
  bar = sub_string("foobar"s, 3);
}

IMHO the whole design of string_view is a horror show which will take us back to a world of segfaults and angry customers.

update:

Even adding overloads for std::string is a horror show. See if you can spot the subtle segfault timebomb...

#include <string>
#include <string_view>

std::string_view sub_string(std::string_view s, 
  std::size_t p, 
  std::size_t n = std::string_view::npos)
{
  return s.substr(p, n);
}

std::string sub_string(std::string&& s, 
  std::size_t p, 
  std::size_t n = std::string::npos)
{
  return s.substr(p, n);
}

std::string sub_string(std::string const& s, 
  std::size_t p, 
  std::size_t n = std::string::npos)
{
  return s.substr(p, n);
}

int main()
{
  using namespace std::literals;

  auto source = "foobar"s;
  auto bar = sub_string(std::string_view(source), 3);

  // but uh-oh...
  bar = sub_string("foobar"s, 3);
}

The compiler found nothing to warn about here. I am certain that a code review would not either.

I've said it before and I'll say it again, in case anyone on the c++ committee is watching, allowing implicit conversions from std::string to std::string_view is a terrible error which will only serve to bring c++ into disrepute.

Update

Having raised this (to me) rather alarming property of string_view on the cpporg message board, my concerns have been met with indifference.

The consensus of advice from this group is that std::string_view must never be returned from a function, which means that my first offering above is bad form.

There is of course no compiler help to catch times when this happens by accident (for example through template expansion).

As a result, std::string_view should be used with the utmost care, because from a memory management point of view it is equivalent to a copyable pointer pointing into the state of another object, which may no longer exist. However, it looks and behaves in all other respects like a value type.

Thus code like this:

auto s = get_something().get_suffix();

Is safe when get_suffix() returns a std::string (either by value or reference)

but is UB if get_suffix() is ever refactored to return a std::string_view.

Which in my humble view means that any user code that stores returned strings using auto will break if the libraries they are calling are ever refactored to return std::string_view in place of std::string const&.

So from now on, at least for me, "almost always auto" will have to become, "almost always auto, except when it's strings".

27
  • 3
    @sehe updated with an even worse scenario - the result of good intentions going wrong. Expect to see this in a code base near you soon... Sep 4, 2017 at 7:54
  • 10
    @sehe I find it astonishing that the committee did not see this coming. It seems for once they have valued the quick-fix performance improvement of existing algorithms over code-safety. I fear this is a grave error. Sep 4, 2017 at 8:11
  • 4
    Who says they didn't see it coming? It must have been weighing options. I mean, string foo(); bool bar(string_view); auto check = bar(foo()); is safe and reasonable to want to allow.
    – sehe
    Sep 4, 2017 at 8:14
  • 6
    @sehe of course I understand the rationale. It's attractive. It could be achieved safely if string_view were non-copyable and non-moveable. Then you couldn't return one from a function and all would be well. Sep 4, 2017 at 8:17
  • 7
    @geza your question validates my concern very nicely. The second assignment to bar is a string_view constructed from a string_view constructed from a temporary std::string, which has now been destructed. Sep 4, 2017 at 8:45
5

This is how you can efficiently create a sub-string string_view.

#include <string>
inline std::string_view substr_view(const std::string& source, size_t offset = 0,
                std::string_view::size_type count = 
                std::numeric_limits<std::string_view::size_type>::max()) {
    if (offset < source.size()) 
        return std::string_view(source.data() + offset, 
                        std::min(source.size() - offset, count));
    return {};
}

#include <iostream>
int main(void) {
  std::cout << substr_view("abcd",3,11) << "\n";

  std::string s {"0123456789"};
  std::cout << substr_view(s,3,2) << "\n";

  // be cautious about lifetime, as illustrated at https://en.cppreference.com/w/cpp/string/basic_string_view
  std::string_view bad = substr_view("0123456789"s, 3, 2); // "bad" holds a dangling pointer
  std::cout << bad << "\n"; // possible access violation

  return 0;
}
3
  • It might be a good idea to highlight a "bad use", as the given example could easily evolve into one. Proposed an edit to do just that. Jul 26, 2020 at 22:58
  • Prevent the bad case from happening -> std::string_view substr_view(std::string const&&, etc.) = delete; Dec 5, 2020 at 14:25
  • This one should have been marked the correct answer, its the only correct answer on this page. You cannot create a string_view from substr unless you want to keep that substr in memory for the lifetime of your string_view. The accepted answer below is completely incorrect. Jan 6, 2022 at 2:02
0

I realize that the question is about C++17, but it's worth noting that C++20 introduced a string_view constructor that accepts two iterators to char (or whatever the base type is) which allows writing

std::string_view v{ s.begin() +6, s.begin()+6 +5 };

Not sure if there is a cleaner syntax, but it's not difficult to

#define RANGE(_container,_start,_length) (_container).begin() + (_start), (_container).begin() + (_start) + (_length)

for a final

std::string_view v{ RANGE(s,6,5) };

PS: I called RANGE's first parameter _container instead of _string for a reason: the macro can be used with any Container (or class supporting at least begin() and end()), even as part of a function call like

auto pisPosition= std::find( RANGE(myDoubleVector,11,23), std::numbers::pi );

PPS: When possible, prefer C++20's actual ranges library to this poor person's solution.

1
  • However, beware that unlike the substr functions, this has no range validation at all. Mar 15 at 12:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.