传递临时std :: string时的string_view行为 [英] string_view behaviour when passing temporary std::string

查看:169
本文介绍了传递临时std :: string时的string_view行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是遇到了一些误解:
至少在libc ++实现中std :: experimental :: string_view具有以下简洁实现:

I just ran into some misunderstanding: at least in libc++ implementation std::experimental::string_view has the following concise implementation:

template <class _CharT, class _Traits....>
class basic_string_view {
public:
   typedef _CharT value_type;
   ...
   template <class _Allocator>
   basic_string_view(const basic_string<_CharT, _Traits, _Allocator>& str):
       __data(str.data()), __size(str.size())
   {
   }

private:
   const value_type* __data;
   size_type __size;
};

此实现是否表示如果将右值表达式传递给此构造函数,则在使用时会得到未定义的行为__构造后的数据吗?

Does this implementation imply that if we pass rvalue expression to this constructor, we will get undefined behaviour when using __data after construction?

推荐答案

是的。 string_view 是具有引用语义的非所有者包装,必须仅在所引用的字符串超过视图的使用时使用。

That's right. A string_view is a non-owning wrapper with reference semantics that must only be used when the referred string outlives the use of the view.

典型的用例是在函数参数中,实际的字符串在函数调用期间一直存在,并且函数主体从不存储视图,而仅读取

The typical use case is in function parameters where the actual string lives for the duration of the function call and the function body never stores the view, but only reads it:

void foo(std::experimental::string_view message)  // pass by value
{
    std::cout << "You said, '" << message << "'.\n";
}

用法:

foo("Hello");       // OK, string literal has static storage
foo(s);             // OK, s is alive
foo(s.substr(1));   // OK, temporary lives until end of full-expression

的目的是:如果您只需要在函数正文期间插入字符串,为该函数提供一个 string_view 参数,它可以统一绑定到任何类型的字符串参数。您不需要功能模板,复制 string_view s很便宜,并且可以免费获得一些精巧的子字符串操作。相比之下,从不存储 string_view ,但始终存储 string

The moral is: If you only need the string for the duration of the function body, give the function a string_view parameter, and it can uniformly bind to any kind of stringoid argument. You don't need a function template, copying string_views is cheap, and you get some neat substringing operations for free. By contrast, never store a string_view, but always store astring:

struct X
{
    X(std::experimental::string_view s) : s_(s) {}

    std::string s_;     // NEVER have a string_view class member!
};

这篇关于传递临时std :: string时的string_view行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆