Skip to content

C++: return std::string_view instead of char* for variable length strings #550

Closed
@tkohlman

Description

@tkohlman

I nice optimization and/or enhancement would be to return std::string_view instead of const char* for variable length strings. Applications may wish to use a string without copying its bytes somewhere else.

To achieve this now, code must read and save the string's length, then read the string, then construct the string_view.

auto usernameLength = message.usernameLength();
std::string_view username(message.username(), usernameLength);

It cannot be done in a single line, because the length field must be read first. Also note that the length is copied into a uint32_t field twice, once in message.usernameLength() and a second time in message.username(). Returning std::string_view would eliminate one of the copies.

It would be nice to be able to do one of the following:

std::string_view username = message.username();

auto username = message.username();

This might require a C++17 compatibility flag of some kind.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions