dig*_*evo 0 c++ c-strings stdstring micro-optimization string-view
一个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::istringstreamctor 和都std::stoi需要 aconst std::string&作为参数。但我std::string_view使用其data()成员函数向他们传递一个对象。这是不好的做法吗?我应该回到 吗const char*?
但我使用其 data() 成员函数向他们传递一个 std::string_view 对象。这是不好的做法吗
是的,这是一个不好的做法。这很糟糕,主要是因为字符串视图不一定指向以 null 结尾的字符串。如果没有,传递data()到需要空终止的函数将导致未定义的行为。
其次,在某些情况下,预先知道字符串的长度会更有效。长度是已知的,因为它存储在字符串视图中。当您仅用作data()参数时,您不会向函数提供已知的大小。
使用这个代替:std::istringstream iss(std::string{str});
我应该恢复到 const char* 吗?
在这种情况下,我认为没有充分的理由这样做。
| 归档时间: | 
 | 
| 查看次数: | 831 次 | 
| 最近记录: |