0

What is the best way of passing and transferring ownership of a vector and it's data?

In an ideal world, it would work something like this:

std::vector<int>& SpitAVector(int input)
{
    std::vector<int> result;
    result.push_back(input);
    return result;
}

int main()
{
    std::vector<int> myvec;
    myvec = SpitAVector(60);

    std::cout << (int)myvec[0] << std::endl;  //Outputs 60      
}

This doesn't work, since I'm returning a reference to a local variable.

Is it possible to use boost::unique_ptr or boost::shared_ptr to handle this vector output? (Can't use C++11's unique_ptr!)

Mgetz
  • 5,108
  • 2
  • 33
  • 51
Daniel
  • 678
  • 1
  • 5
  • 20

1 Answers1

5

What is the best way of passing and transferring ownership of a vector and it's data?

Return the vector by value.

In C++11 or later, the return value will be moved (if necessary), so there certainly won't be a bulk data copy.

If you're stuck in the past, then make sure you meet the criteria for copy elision of the return value. Your function, with a single return point, does. Although it's not required to, any decent compiler will perform that optimisation.

Is it possible to use boost::unique_ptr or boost::shared_ptr to handle this vector output?

Yes, but that would be unnecessarily complicated. Just return by value.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
  • This vector should hold about 260 MB of data. I'm assuming returning by value won't cause a copy then – Daniel Nov 12 '14 at 17:05
  • 1
    @Daniel: It won't if you're using C++11 (with move semantics), or have a single return point (as you do here). I'm just writing some details about that. – Mike Seymour Nov 12 '14 at 17:06
  • 2
    @Daniel Most compilers these days implement return value optimization (RVO), which will cause the vector to be constructed in the stack space of the calling function where it would be returned to -- there won't be a copy-construction, nor even a move-construction. – cdhowie Nov 12 '14 at 17:07