2 vector objects pointing to the same allocated memory

僤鯓⒐⒋嵵緔 提交于 2019-12-13 09:13:43

问题


In C++, how to make a copy of an existing vector pointing to the same allocated memory ?

e.g :

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

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 ?


回答1:


There is a boost::shared_array template.

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< vector< int > >

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 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:


make o2 a reference to o1

std::vector<int> &o2 = o1;


来源:https://stackoverflow.com/questions/13341311/2-vector-objects-pointing-to-the-same-allocated-memory

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!