如何使istringstream更有效?

时间:2016-12-07 04:17:41

标签: c++ performance standards c++17

#include <sstream>

using namespace std;

const char* GetHugeString();

int main()
{
    const char* p = GetHugeString();

    //
    // Below will copy the huge string into a std::string object!
    // 
    istringstream sstrm{p}; 

    return {};
}

istringstream不需要大字符串的副本;以null结尾的字符串指针就足够了。但istringstream的{​​{1}}只取ctor而不是std::string(仅限c ++ 1z)作为其论据。

在这种情况下,是否有办法让std::string_view更有效率?

1 个答案:

答案 0 :(得分:3)

您可以简单地分配istringstream

内部使用的缓冲区
istringstream stream;
stream.rdbuf()->pubsetbuf(p, strlen(p));

这不会复制字符串。请注意pubsetbuf()希望char*不是const char*,但它实际上并没有修改字符串,所以在传递之前你可能const_cast你的C字符串指针。

相关问题