本文介绍了是否可以使用一个std :: string的read()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以对read()使用std :: string?

Is it possible to use an std::string for read() ?

示例:

std::string data;

read(fd, data, 42);

Normaly,我们必须使用char *,但是可以直接使用std :: string吗? (我不喜欢不创建一个char *来存储结果)

Normaly, we have to use char* but is it possible to directly use a std::string ? (I prefer don't create a char* for store the result)

谢谢

推荐答案

好吧,你需要创建一个 char * 不知何故,因为这是
函数需要的。 (BTW:你在说Posix函数
read ,不是你,而不是 std :: istream :: read ?)问题不是
char * ,它是 char * 指向(我怀疑是什么
你的意思)。

Well, you'll need to create a char* somehow, since that's what thefunction requires. (BTW: you are talking about the Posix functionread, aren't you, and not std::istream::read?) The problem isn'tthe char*, it's what the char* points to (which I suspect is whatyou actually meant).

这里最简单和通常的解决方案是使用本地数组:

The simplest and usual solution here would be to use a local array:

char buffer[43];
int len = read(fd, buffer, 42);
if ( len < 0 ) {
    //  read error...
} else if ( len == 0 ) {
    //  eof...
} else {
    std::string data(buffer, len);
}

如果要直接捕获到 std: :string ,但是,这是
可能(虽然不一定是个好主意):

If you want to capture directly into an std::string, however, this ispossible (although not necessarily a good idea):

std::string data;
data.resize( 42 );
int len = read( fd, &data[0], data.size() );
//  error handling as above...
data.resize( len );  //  If no error...

这避免了复制,但坦率地说...复制与实际读取所需的时间和字符串中的存储器的
分配相比是微不足道的。这也有(可能
可忽略的)结果字符串的实际缓冲区
的42字节(向上舍入到任何),而不只是最小
实际读取的字符。

This avoids the copy, but quite frankly... The copy is insignificantcompared to the time necessary for the actual read and for theallocation of the memory in the string. This also has the (probablynegligible) disadvantage of the resulting string having an actual bufferof 42 bytes (rounded up to whatever), rather than just the minimumnecessary for the characters actually read.

(因为人们有时提出这个问题,关于 std:; string :这是一个问题十个或更多
年前。 std :: string 的原始规范设计为
表示允许非连续的实现,沿着
的线,然后流行的 rope 类。在实践中,没有实现者发现这个
是有用的,开始假设连续性,在这一点上,标准委员会决定将标准与现有的
做法相一致,并要求邻接性。所以...没有实现过,没有
是连续的,未来的实现将放弃连续性,
给出了C ++ 11中的要求。)

(And since people sometimes raise the issue, with regards to thecontiguity of the memory in std:;string: this was an issue ten or moreyears ago. The original specifications for std::string were designedexpressedly to allow non-contiguous implementations, along the lines ofthe then popular rope class. In practice, no implementor found thisto be useful, and people did start assuming contiguity. At which point,the standards committee decided to align the standard with existingpractice, and require contiguity. So... no implementation has ever notbeen contiguous, and no future implementation will forego contiguity,given the requirements in C++11.)

这篇关于是否可以使用一个std :: string的read()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-07 06:40