我遇到过这样的情况,我得到一个 std::vector<char>
第三方库输出的数据,是一个非常大的长度数据,然后我需要把它转换成pybind11::array
对象,我不想分配内存并执行 memcpy
,那根本没有效率。
现在我知道我可以获得 std::vector<char>
缓冲区地址,但我不知道如何释放 vector 的所有权,因此当 vector 对象被破坏时缓冲区不会释放,我想知道是否有办法实现这一点。
我在下面写了一个测试代码来测试,但是失败了
#include<vector>
#include<iostream>
int *got_vec(int len){// the len in actually scene is decided by the thirdparty lib
std::vector<int> vec;
for(int i =0;i<len;i++){
vec.push_back(i);
}
int *p_vec = &vec[0];
std::move(vec);
return p_vec;
}
int main(int argc,const char **argv){
int len=atoi(argv[1]);
std::cout<<"will go allocate memory size:"<<len<<", before allocation"<<std::endl;
int *p_vec = got_vec(len);
std::cout<<"after allocation, go to print value"<<std::endl;
for(int i = 0; i < len;i++)
std::cout<<p_vec[i]<<",";
std::cout<<std::endl;
delete p_vec;
std::cout<<"deleted"<<std::endl;
}
程序崩溃于 std::cout<<p_vec[i]<<",";
最佳答案
std::vector 不允许分离底层缓冲区。你也可以看看taking over memory from std::vector对于类似的问题。
关于c++ - 如何将所有权从 C++ std::vector<char> 转移到 char *pointer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60429385/