` 从 `std::string` 窃取内存,c++,stdvector,move-semantics,stringstream,rvalue-reference"/>

首页 > 解决方案 > 让一个`std::vector` 从 `std::string` 窃取内存

问题描述

假设我们有std::string s一个原始数据缓冲区,但我们想要std::vector<uint8_t> v。缓冲区长度以百万计。有没有一种简单的方法可以让v窃取s内存从而避免复制缓冲区?

就像std::vector<uint8_t>::vector(std::string&&)会做的那样,但以某种方式从 STL 外部进行。

或者,是否有可能vstd::stringstream ss与效率一样高的操作中获得ss.str()

标签: c++stdvectormove-semanticsstringstreamrvalue-reference

解决方案


好的,那里有很多评论,让我们尝试将一些东西放在一起,因为我需要练习并且可能会获得一些积分[更新:没有:(]。

我对“现代 C++”还很陌生,所以请在找到时接受它。可能需要到 C++17,我没有仔细检查过。任何批评都非常受欢迎,但我更愿意编辑我自己的帖子。请记住,在阅读本文时,OP真正想要做的是从文件中读取他的字节。谢谢。

更新:根据@Deduplicator 下面的评论,调整以处理文件大小在调用stat()和调用之间发生变化的情况fread()......随后替换freadstd::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;
}

现场演示。当然,没有可读取的实际文件,所以...


另外:您是否考虑过编写自己的简单容器来映射文件视图?只是一个想法。


推荐阅读