21

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.

4

3 回答 3

29

无需使用 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() ) );
于 2019-12-20T11:49:16.610 回答
1

第一种方法正确吗?

是的,因为strVw返回相同string_view的 s:它们都指向相同的m_V并且具有相同的大小。

这里的正确性取决于如何strVw实现。

或者我必须使用第二个?

我会创建一个转换函数:

inline std::string as_string(std::string_view v) { 
    return {v.data(), v.size()}; 
}

并使用它:

loadData(as_string(symbol.strVw()));

无论strVw实施如何,此方法都是安全的。

于 2019-12-20T11:25:01.977 回答
1

如果您想将 C++ 中的一些 string_view 转换为字符串格式(例如,您可以在完成所有分析后返回到函数),您可以通过以下操作进行更改:

string_view sv;
string s = {sv.begin(), sv.end()};

反过来,要从字符串中获取 string_view (以便获取指向该字符串的指针),您可以这样做:

string s;
string_view sv = string_view(s);

请注意,可以对 string_view 执行 substring 和各种其他操作,就像对 string 一样。

于 2020-06-19T20:04:59.843 回答