2016-12-07 1 views
1
#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巨大な文字列のコピーは必要ありません。ヌルで終了する文字列ポインタで十分です。しかし、istringstreamctorは、その引数としてstd::string_view(C++ 1zのみ)ではなく、std::stringとなります。istringstreamをより効率的にするには?

std::istringstreamをこのような場合に効率的にする回避策はありますか?

+0

これは理由はわかりませんが、内部ストレージが 'string_view'を受け入れない' stringbuf'によってバックアップされているため、これはサポートされていないと思われます。 –

答えて

2

あなたは、単にistringstreamに内部で使用されるバッファを割り当てることができます。

istringstream stream; 
stream.rdbuf()->pubsetbuf(p, strlen(p)); 

これは、文字列をコピーしません。 pubsetbuf()char*const char*ではないことを願っていますが、実際には文字列を変更しないので、渡す前にCの文字列ポインタconst_castがある可能性があります。

+2

あなたが提案しているものは[実装定義の振舞いを持っています](http://stackoverflow.com/a/13059195/636019)。 – ildjarn

関連する問題