问题描述
我有一堂课
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
并且有一个我无法修改的lib-func:
and there is a lib-func that I can't modify:
extern bool loadData( const string& strSymbol );
如果有局部变量:
Symbol_t symbol( "123456" );
当我需要调用loadData时,我不敢这样做:
When I need to call loadData, I dare not do it like this:
loadData( string( symbol.strVw().begin(), symbol.strVw().end() ) );
我必须这样做:
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?
因为我认为在方法1中,传递给std :: string的构造函数的迭代器是两个不同的string_vew对象,并且即使从几乎所有的C ++编译器.
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'tor获取范围. std::string
具有根据std::string_view
,数字10 在列表中.效果是
There is no need to use the c'tor taking a range. std::string
has a constructor that operates in terms of std::string_view
, number 10 in the list. The effect of which is
template < class T >
explicit basic_string( const T& t, const Allocator& alloc = Allocator() );
就像通过std::basic_string_view<CharT, Traits> sv = t;
一样,将t转换为字符串视图sv,然后使用sv
的内容来初始化字符串,就像通过basic_string(sv.data(), sv.size(), alloc)
一样.仅当std::is_convertible_v<const T&, std::basic_string_view<CharT, Traits>>
为true和std::is_convertible_v<const T&, const CharT*>
为false时,此重载才参与重载解决方案.
Implicitly converts t to a string view sv as if by std::basic_string_view<CharT, Traits> sv = t;
, then initializes the string with the contents of sv
, as if by basic_string(sv.data(), sv.size(), alloc)
. This overload only participates in overload resolution if std::is_convertible_v<const T&, std::basic_string_view<CharT, Traits>>
is true and std::is_convertible_v<const T&, const CharT*>
is false.
由于两个条件都适用于std::string_view
本身,因此我们可以简单地将调用写入loadData
:
Since both conditions hold for std::string_view
itself, we can write the call to loadData
as simply:
loadData( std::string( symbol.strVw() ) );
这篇关于如何从std :: string_view正确创建std :: string?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!