问题描述
在C ++中,如何复制指向相同分配内存的现有向量?
In C++, how to make a copy of an existing vector pointing to the same allocated memory ?
例如:
vector<int> o1;
o1.push_back(1);
vector<int> o2;
//Make o2 share same memory as o1
o2[0]=2;
cout << o1[0]; //display 2
编辑:我不清楚目标:如果o1分配给堆并被销毁,如何创建一个对象o2,该对象将指向与o1相同的已分配内存,以使其保持在o1范围之外?
EDIT : I haven't been clear about the objective : if o1 is allocated on the heap and gets destroyed, how can I create an object o2 that would point to the same allocated memory as o1 to keep it outside of the o1 scope ?
推荐答案
有一个 boost :: shared_array
模板。
但这共享一个固定的-大小的数据数组,您不能修改大小。
This however shares a fixed-size array of data and you cannot modify the size.
如果要共享可调整大小的矢量,请使用
If you want to share a resizeable vector then use
boost :: shared_ptr<向量<整数> >
您还可以做的是将向量存储器 swap
换成另一个
What you can also do is swap
the vector memory into a different vector.
{
std::vector< int > o1; // on the stack
// fill o1
std::vector< int > * o2 = new std::vector< int >; // on the heap
o2->swap( o1 );
// save o2 somewhere or return it
} // o2 now owns the exact memory that o1 had as o1 loses scope
C ++ 11
将引入移动语义,允许您使用 std :: move 因此
C++11
will bring in "move" semantics allowing you to keep the actual memory in o1 with std::move
thus
std::vector<int> && foo()
{
std::vector<int> o1;
// fill o1
return std::move( o1 );
}
// from somewhere else
std::vector< int > o2( foo() );
这篇关于2个指向相同分配内存的矢量对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!