【发布时间】:2022-01-06 17:24:44
【问题描述】:
std::string_view 参数是否优于下面代码中的 const char* 参数?
void func( const std::string_view str )
{
std::istringstream iss( str.data( ) ); // str is passed to the ctor of istringstream
std::size_t pos { };
int num { std::stoi( str.data( ), &pos, 10 ) }; // and here it's passed to std::stoi
}
int main()
{
std::array<char, 20> buffer { };
std::cin.getline( buffer.data( ), 20 );
func( buffer.data( ) );
}
std::istringstream ctor 和 std::stoi 都需要 const std::string& 作为参数。但我使用 data() 成员函数向他们传递了一个 std::string_view 对象。这是不好的做法吗?我应该回到const char*吗?
【问题讨论】:
-
应该可以通过阅读
std::string_view的文档,特别是其构造函数的文档来找出答案,并花点时间思考构造函数以这种方式工作的含义.仅基于所示代码中引用的所有对象的构造函数的公共规范,应该相当简单地确定发生了什么,以及通过避免使用string_view并改为传递普通指针是否有任何改进.您是否尝试过像这样用笔和纸解决所有问题? -
考虑使用
std::string{str}而不是str.data( )来构造std::istringstream iss。在这两种情况下,您都在构造std::string,但如果没有空终止字节,str.data()将导致问题。
标签: c++ c-strings stdstring micro-optimization string-view