我在 C 中有一個函式,它將 HTTP 請求正文的內容讀入std::string.
我想出了以下代碼:
void handle_request_body(int connfd, HttpRequest &req) {
unsigned long size_to_read;
try {
size_to_read = std::stoul(req.headers().at("content-length"));
} catch (std::out_of_range const &) {
return;
}
char *buf = new char[size_to_read 1];
memset(buf, 0, size_to_read 1);
read(connfd, buf, size_to_read);
req._body.append(buf);
delete[] buf;
}
這對我來說有點難看,因為我必須使用new可變大小的陣列,因為不允許使用。然后我嘗試使用以下代碼直接讀取字串:
void handle_request_body(int connfd, HttpRequest &req) {
unsigned long size_to_read;
try {
size_to_read = std::stoul(req.headers().at("content-length"));
} catch (std::out_of_range const &) {
return;
}
std::string buf(size_to_read 1, 0);
read(connfd, buf.data(), size_to_read);
req._body = buf;
}
我發現第二種方法更干凈,但我擔心std::string使用它的data()方法直接讀入 a 是否被認為是不好的做法。
有一個更好的方法嗎?非常感謝任何見解!
uj5u.com熱心網友回復:
真的取決于你的閱讀功能在幕后做了什么。
如果您可以控制讀取功能,我強烈建議您不要使用指標,而是使用對 std 容器的類參考。可調整大小的標準容器不保證指標將繼續指向相同的記憶體,即如果它重新分配它的大小,您的指標將不再有效。在這個例子中這很好,因為沒有其他人接觸它,但在許多其他應用程式中,這將是非常不安全的!
就像是:
void read(int id, std::string& dest, int readLength){
//whatever code gets the data stream
dest = data;
}
如果它必須是某些 OS API 呼叫的 C 樣式緩沖區,最好使用唯一的字符指標,讓記憶體自行清理。
std::unique_ptr<char[]> buffer = std::make_unique<char[]>(size 1);
memset(&buffer[0], 0, size 1);
我不建議從作業系統中逐個字符地讀取,因為與一次讀取所有呼叫相比,這通常會對每次呼叫產生巨大的性能開銷。
uj5u.com熱心網友回復:
正如@Galik 評論的那樣。這是基于意見的。
但我們可以說的是:
- 在 C 中,我們不應該對擁有的記憶體使用原始指標
new并且delete應該避免- 應避免使用 C 樣式陣列
- 閱讀
data()將起作用,但不是那么好(我的觀點)。無論如何,比使用new和創建記憶體泄漏要好。
您可以在一個簡單的for回圈中從檔案中一個接一個地讀取一個位元組,然后將每個位元組添加到std::stringwith 中 =。但這也很笨拙。
如果允許您使用 C 語言和庫,那最好。
順便提一句。std::string也是一個“變長陣列”
建議:使用您的第二個解決方案
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/495271.html
