1

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
    You cannot. There is no way to make the proposed solution work. There may be a solution to the currently undisclosed problem, but the requirements need to be made clear. – R. Martinho Fernandes Nov 12 '12 at 09:40
  • 2
    You could make `o2` a reference: `vector& o2(o1);` – hmjd Nov 12 '12 at 09:41
  • either use shared_ptr > or boost::shared_array< int > although with boost::shared_array you cannot resize your array. – CashCow Nov 12 '12 at 10:55

2 Answers2

3

make o2 a reference to o1

std::vector<int> &o2 = o1;
billz
  • 44,644
  • 9
  • 83
  • 100
0

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() );
CashCow
  • 30,981
  • 5
  • 61
  • 92