![](/img/trans.png)
[英]Initialization of std::string from std::vector<unsigned char> causes error
[英]Letting a `std::vector<unsigned char>` steal memory from a `std::string`
假設我們有std::string s
持有原始數據緩沖區,但我們想要std::vector<uint8_t> v
代替。 緩沖區長度以百萬計。 有沒有一種簡單的方法可以讓v
竊取s
的內存,從而避免復制緩沖區?
就像std::vector<uint8_t>::vector(std::string&&)
那樣,但是從STL的外部以某種方式進行。
或者,是否可以通過與ss.str()
一樣有效的操作從std::stringstream ss
獲取v
?
好,那里有很多評論,讓我們嘗試將它們放在一起,因為我需要練習,並且可能會獲得一些積分[更新:沒有:(]。
我對“現代C ++”還不陌生,因此請隨便使用。 可能需要遲到C ++ 17,我還沒有仔細檢查過。 任何批評都值得歡迎,但我希望編輯自己的帖子。 並且在閱讀本文時請記住,OP 實際要執行的操作是從文件中讀取其字節。 謝謝。
更新:調整以處理以下情況,即文件大小根據下面@Deduplicator的注釋在stat()
調用與fread()
調用之間改變...然后將fread
替換為std::ifstream
,我認為現在在那里。
#include <string>
#include <vector>
#include <optional>
#include <iostream>
#include <fstream>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
using optional_vector_of_char = std::optional <std::vector <char>>;
// Read file into a std::optional <std::vector <char>>.
// Now handles the file size changing when we're not looking.
optional_vector_of_char SmarterReadFileIntoVector (std::string filename)
{
for ( ; ; )
{
struct stat stat_buf;
int err = stat (filename.c_str (), &stat_buf);
if (err)
{
// handle the error
return optional_vector_of_char (); // or maybe throw an exception
}
size_t filesize = stat_buf.st_size;
std::ifstream fs;
fs.open (filename, std::ios_base::in | std::ios_base::binary);
if (!fs.is_open ())
{
// handle the error
return optional_vector_of_char ();
}
optional_vector_of_char v (filesize + 1);
std::vector <char>& vecref = v.value ();
fs.read (vecref.data (), filesize + 1);
if (fs.rdstate () & std::ifstream::failbit)
{
// handle the error
return optional_vector_of_char ();
}
size_t bytes_read = fs.gcount ();
if (bytes_read <= filesize) // file same size or shrunk, this code handles both
{
vecref.resize (bytes_read);
vecref.shrink_to_fit ();
return v; // RVO
}
// File has grown, go round again
}
}
int main ()
{
optional_vector_of_char v = SmarterReadFileIntoVector ("abcde");
std::cout << std::boolalpha << v.has_value () << std::endl;
}
現場演示 。 當然沒有可用的實際文件可供讀取,因此...
另外 :您是否考慮過編寫自己的簡單容器來映射文件視圖? 只是一個想法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.