【问题标题】:string_view Vs const char* performancestring_view 与 const char* 性能
【发布时间】: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&amp; 作为参数。但我使用 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


【解决方案1】:

但是我使用它的 data() 成员函数向他们传递了一个 std::string_view 对象。这是不好的做法吗

是的,这是一种不好的做法。这很糟糕,主要是因为字符串视图不一定指向以空值结尾的字符串。如果没有,将data() 传递给需要空终止的函数将导致未定义的行为。

其次,在某些情况下,事先知道字符串的长度会更有效。长度是已知的,因为它存储在字符串视图中。当您仅将 data() 用作参数时,您并未向函数提供已知大小。

改用这个:std::istringstream iss(std::string{str});

我应该恢复为 const char* 吗?

在这种情况下,我认为没有充分的理由这样做。

【讨论】:

  • std::cin.get 接收用户的字符串,据我所知 null 终止它。所以我不担心。但是std::istringstream iss(std::string{str}); 和通过const char* 一样有效吗?我的意思是它会创建一个临时的std::string
  • @digito_evo std::cin.get receives the user's string and null terminates it as far as I know. 这和func 有什么关系?没有什么可以阻止 func 被调用时使用 std::cin.get 未收到的字符串。
  • @digito_evo But is std::istringstream iss(std::string{str}); as efficient as passing a const char*? 测量并找出答案。我会预测任何差异都会小于噪音。
  • @digito_evo does passing it to iss ctor the way you showed, have any benefits? 理论上可能。但这并不意味着差异足以衡量。 I mean will it prevent iss from reallocating its internal buffer? 我不认为 iss 无论如何都需要重新分配。 Will iss first 可以查看来源进行验证。我看不出它为什么不能。 Also how can this affect stois performance? 可能以同样的方式。 Should I do the same thing for that too? 是的,你还在构造字符串,data() 可能会导致 UB。
  • @digito_evo 澄清一点,issstoi 之间没有区别。区别——如果有的话——在字符串构造函数中。
猜你喜欢
  • 2021-02-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多