首页 > 解决方案 > How to correctly create std::string from a std::string_view?

问题描述

I have a class:

class Symbol_t {
public:
   Symbol_t( const char* rawName ) {
      memcpy( m_V, rawName, 6 * sizeof( char ) );
   };

   string_view strVw() const {
      return string_view( m_V, 6 );
   };

private:
   char m_V[6];

}; // class Symbol_t

and there is a lib-func that I can't modify:

extern bool loadData( const string& strSymbol );

If there is a local variable:

Symbol_t   symbol( "123456" );

When I need to call loadData, I dare not do it like this:

loadData( string( symbol.strVw().begin(), symbol.strVw().end() ) );

I have to do like this:

string_view svwSym = symbol.strVw();
loadData( string( svw.begin(), svw.end() ) );

My question: Is the first method correct? or I must use the second one?

Because I think that in Method 1, the iterators I passed to the constructor of std::string, are of two Different string_vew objects, and theoretically the result is undefined, even though we would get expected result with almost all of the C++ compilers.

Any hints will be appreciated! thanks.

标签: c++stringiteratorc++17string-view

解决方案


无需使用 c'tor 获取范围。std::string有一个根据std::string_view,列表中的第 10 号进行操作的构造函数。其中的效果是

template < class T >
explicit basic_string( const T& t, const Allocator& alloc = Allocator() ); 

隐式地将 t 转换为字符串视图 sv,就像 by 一样std::basic_string_view<CharT, Traits> sv = t;,然后用 的内容初始化字符串sv,就像 by 一样basic_string(sv.data(), sv.size(), alloc)std::is_convertible_v<const T&, std::basic_string_view<CharT, Traits>>此重载仅在为真和std::is_convertible_v<const T&, const CharT*>为假时才参与重载决议。

由于这两个条件都成立std::string_view,我们可以loadData简单地编写调用:

loadData( std::string( symbol.strVw() ) );

推荐阅读