std::string に read(2) で書き込む
くそ... ググってみたら std::string
の中の人は連続性が事実上 保証されているそうじゃないか...
- http://debugfailure.wordpress.com/2009/11/20/is-stdstrings-storage-contiguous/ Is std::string’s storage contiguous? << Systemfault's Weblog
- http://stackoverflow.com/questions/1986966/does-s0-point-to-contiguous-characters-in-a-stdstring Does "&s[0]" point to contiguous characters in a std::string? - Stack Overflow
(そしてC++0xでは陽に保証されるように変わるとも)
つまり堂々と
m_str.resize(BUF_LEN);
read(fd, &m_str[0], BUF_LEN);
と書けるということ.あぁ,同様の局面で使うためにがんばって補助クラスをこさえたのに.まぁSGIのropeか何かに使うか...
これがその補助クラスだ:
class StringAdapter { std::string &str; std::vector<char> buf; StringAdapter(std::string &s, size_t l) : str(s), buf(l + 1) { } ~StringAdapter() { buf.back() = '\0'; // 安全ネット str.assign(buf.data()); } operator void*() { return buf.data(); } };
これを使えば,内部バッファが連続してない std::string
の変種に対しても,
read(fd, StringAdapter(m_str, BUF_LEN), BUF_LEN);
と書ける... というつもりで作った.ちょっと試した範囲では間違ってないと思うんだけど,どうでしょうか.C++使いはこういうテク(もしくはもっと洗練されたテク)を何という呼び名で読んでるのか知りたい.代わりに std::vector
の内部バッファの連続性を利用していて,諸手続きの自動化をC++の機能(参照,型変換オペレータやらctor/dtor)を利用して行っている.メソッド std::string::assign
は,提供されることは仮定して良かろう.STL algorithmの copy
辺りでもよかったか.
内部バッファの連続性を仮定できないと
{ char buf[BUF_LEN + 1]; read(0, buf, BUF_LEN); buf[BUF_LEN] = '\0'; // 安全ネット m_str.assign(buf); }
みたいにダサいことになるので,それを回避したかったのだが,まぁ意味なかったね...
あと,まさかと思うが read(2)
の返り値チェックは省かないように.