User Tools

Site Tools


cplusplus:string_view

This is an old revision of the document!


String_view for objects with a const string field

Store a little string in an object which is going to be its name. It can't change its name, so it ought to be const. Prefer not to use std::string - it's heavyweight, and the data ends up on a separate string allocation.

struct Str {
    constexpr Str(std::string_view s) : buf{[&]{
        auto buf = std::array<char, 64>{};
        std::copy(s.begin(), s.end(), buf.data());
        return buf;
    }()}, sv{buf.data()} {}
 
    std::array<char, 64> const buf;
    std::string_view const sv;
};
cplusplus/string_view.1651209818.txt.gz · Last modified: 2023/04/12 20:44 (external edit)