Using std::string_view with api, what expects null terminated string

前端 未结 3 1676
予麋鹿
予麋鹿 2020-12-11 01:26

I have a method that takes std::string_view and uses function, which takes null terminated string as parameter. For example:

void stringFunc(std         


        
3条回答
  •  温柔的废话
    2020-12-11 01:40

    You cannot alter a string through std::string_view. Therefore you cannot add a terminating '\0' character. Hence you need to copy the string somewhere else to add a '\0'-terminator. You could avoid heap allocations by putting the string on the stack, if it's short enough. If you know, that the std::string_view is part of a null-terminated string, then you may check, if the character past the end is a '\0' character and avoid the copy in that case. Other than that, I don't see much more room for optimizations.

提交回复
热议问题