Does passing a vector reference transfer ownership of its data?

868 views Asked by At

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!)

1

There are 1 answers

3
Mike Seymour On

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.