c++ - 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'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() ) );
推荐阅读
- r - 按特定行数分配唯一编号 R
- python - pdb 是否具有像 gdb 这样的布局 src?
- vbscript - 每 10 秒在 Web 服务器中上传文件时出错
- windows - 如何根据带有序号的文本文件批量制作文件夹
- igraph - 合并/删除边缘
- python - 在 ubuntu ec2 深度学习实例中通过 jupyter notebook 从 s3 读取数据
- javascript - 修改现有 MapView 填充属性
- ecto - 在分区 MySQL 表的特定分区上运行查询
- recursion - 下面递归函数的迭代函数是什么
- javascript - 如何在使用 javascript 滚动到页面时向这些链接添加活动类?