我可以重新解释 std::vector<char>作为 std::vector<unsigned char>不复制? [英] Can I reinterpret std::vector&lt;char&gt; as a std::vector&lt;unsigned char&gt; without copying?

查看:41
本文介绍了我可以重新解释 std::vector<char>作为 std::vector<unsigned char>不复制?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对 std::vector 的引用,我想将其用作接受 std::vector 的函数的参数.我可以在不复制的情况下做到这一点吗?

I have a reference to std::vector<char> that I want to use as a parameter to a function which accepts std::vector<unsigned char>. Can I do this without copying?

我有以下功能并且可以正常工作;但是我不确定是否真的发生了副本 - 有人可以帮助我理解这一点吗?是否可以使用 std::move 来避免复制或者它已经没有被复制?

I have following function and it works; however I am not sure if a copy actually takes place - could someone help me understanding this? Is it possible to use std::move to avoid copy or is it already not being copied?

static void showDataBlock(bool usefold, bool usecolor,
            std::vector<char> &chunkdata)  
{
  char* buf = chunkdata.data();                      
  unsigned char* membuf = reinterpret_cast<unsigned char*>(buf); 
  std::vector<unsigned char> vec(membuf, membuf + chunkdata.size()); 
  showDataBlock(usefold, usecolor, vec);   
} 

我以为我可以写:

std::vector<unsigned char> vec(std::move(membuf),
                               std::move(membuf) + chunkdata.size());  

这是矫枉过正吗?实际发生了什么?

Is this overkill? What actually happens?

推荐答案

...是否可以使用 std::move 来避免复制,或者已经不是被复制

...is it possible to use std::move to avoid copy or is it already not being copied

您不能在两个不相关的容器之间移动.std::vectornot std::vector.因此没有合法的方法可以在 O(1) 时间内移动~转换"一个内容到另一个内容.

You cannot move between two unrelated containers. a std::vector<char> is not a std::vector<unsigned char>. And hence there is no legal way to "move ~ convert" the contents of one to another in O(1) time.

您可以复制:

void showData( std::vector<char>& data){
    std::vector<unsigned char> udata(data.begin(), data.end());
    for(auto& x : udata)
        modify( x );
    ....
}

或为每次访问实时投射...

or cast it in realtime for each access...

inline unsigned char& as_uchar(char& ch){
    return reinterpret_cast<unsigned char&>(ch);
}

void showDataBlock(std::vector<char>& data){
    for(auto& x : data){
        modify( as_uchar(x) );
    }
}

这篇关于我可以重新解释 std::vector<char>作为 std::vector<unsigned char>不复制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆