João Pires
João Pires

Reputation: 1007

How to return a constant view of a std::string?

While prototyping and playing around in C++, trying some concepts for making a utf8-aware immutable string, I stood with the following dilemma:

Is there any way to return a immutable view of a string. Like, instead of returning a substring, I want to be able to return a substring that references a part of the original string.

// Just some quick prototyping of ideas.
// Heavier than just a normal string.
// Construction would be heavier too because of the indices vector.
// Size would end up being O1 though.
// Indexing would also be faster.

struct ustring {
    std::string data;
    std::vector<size_t> indices;

    // How do I return a view to a string?

    std::string operator [](size_t const i) const {
        return data.substr(indices[i], indices[i + 1] - indices[i]);
    }
};

Upvotes: 3

Views: 2075

Answers (1)

Travis Gockel
Travis Gockel

Reputation: 27633

Sounds like std::string_view is the class for you! If you don't have C++17 support, then try out std::experimental::string_view. If that's not available, try out boost::string_view. All of those choices can be used in the same way (just replace std::string_view with whatever you use):

std::string_view operator [](size_t const i) const {
    return std::string_view(&data[i], 1);
}

Welcome to C++, where there's always another kitchen sink!

Upvotes: 5

Related Questions