2 vector objects pointing to the same allocated me

2019-09-21 17:09发布

问题:

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;


标签: c++ vector copy