我什么时候可以通过const& std :: string而不是std :: string

编程入门 行业动态 更新时间:2024-10-09 07:19:56
本文介绍了我什么时候可以通过const& std :: string而不是std :: string_view?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我了解使用 std :: string_view 的动机; 可以帮助避免在函数参数中进行不必要的分配。

I understand the motivation for using std::string_view; it can help avoid unecessary allocations in function arguments.

例如: 以下程序将创建 std :: string 来自字符串文字。 这会导致不希望的动态分配,因为我们只对观察字符感兴趣。

For example: The following program will create a std::string from a string literal. This causes an undesired dynamic allocation, as we are only interested observing the characters.

#include <iostream> void* operator new(std::size_t n) { std::cout << "[allocating " << n << " bytes]\n"; return malloc(n); } void observe_string(std::string const& str){} int main(){ observe_string("hello world"); //prints [allocating 36 bytes] }

使用 string_view 将解决问题:

#include <iostream> #include <experimental/string_view> void* operator new(std::size_t n) { std::cout << "[allocating " << n << " bytes]\n"; return malloc(n); } void observe_string(std::experimental::string_view const& str){ } int main(){ observe_string("hello world"); //prints nothing }

此 我什么时候选择const&的std :: string?

看看 std :: string_view 的接口,它代替了函数参数的string_view?似乎我可以替换所有由 const& 传递的 std :: string 实例。有什么反例吗?

Looking at the interface of std::string_view, it looks as though I could replace all instances of std::string that are passed by const&. Are there any counter examples to this? Is std::string_view meant to replace std::string const& for parameter passing?

推荐答案

我何时选择 std :: string c $ c> const& 而不是 string_view 作为函数参数?

When would I choose std::string by const& instead of string_view for function arguments?

您是否需要以空值结尾的字符串?如果是这样,则应该使用 std :: string const& 来保证。 string_view 不会-只是 const char 的范围。

Do you need a null-terminated string? If so, then you should use std::string const& which gives you that guarantee. string_view does not - it's simply a range of const char.

如果不需要需要以null结尾的字符串,并且不需要获取数据所有权,则应使用 string_view 。如果确实需要获取数据所有权,则按值 string 可能比 string_view 。

If you do not need a null-terminated string, and you do not need to take ownership of the data, then you should use string_view. If you do need to take ownership of the data, then it may be the case that string by value is better than string_view.

更多推荐

我什么时候可以通过const&amp; std :: string而不是std :: string

本文发布于:2023-11-24 16:55:09,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1626058.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:什么时候   而不是   const   amp   std

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!