我想使用服务器的 c++ httplib 功能向内容提供商发送内容。
但我想将它与智能指针一起使用,因为之前的计算是在调度之前进行的。
如果我简化 httplib 示例,这就是我正在做的事情:
const size_t DATA_CHUNK_SIZE = 4;
svr.Get("/stream", [&](const Request &req, Response &res) {
auto data = std::make_shared_for_overwrite<char[]>(DATA_CHUNK_SIZE);
// doing calculation which potentially fail
if (!create_data_string(data, DATA_CHUNK_SIZE)) {
// return an error
return;
}
res.set_content_provider(
DATA_CHUNK_SIZE, // Content length
"text/plain", // Content type
[&, data](size_t offset, size_t length, DataSink &sink) {
sink.write(&data[offset], std::min(length, DATA_CHUNK_SIZE));
return true; // return 'false' if you want to cancel the process.
},
[data](bool success) { /* data will be released after the call */ });
});
该方法正在运行并经过真实内容的测试,但我不知道这样做是否是最好的。
你觉得怎么样?我需要对该代码片段进行代码审查。
代码正确并且没有出现内存泄漏。当
Response res
处于活动状态时,内容提供者和资源释放者闭包处于活动状态,并且当读取所有数据时它们都会被销毁。