传递和转移 vector 及其数据的所有权的最佳方式是什么?
在理想世界中,它会像这样工作:
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
}
这不起作用,因为我要返回对局部变量的引用。
是否可以使用 boost::unique_ptr
或 boost::shared_ptr
来处理这个 vector 输出? (不能使用 C++11 的 unique_ptr!)
最佳答案
What is the best way of passing and transferring ownership of a vector and it's data?
按值返回 vector 。
在 C++11 或更高版本中,返回值将被移动(如果需要),因此肯定不会有批量数据复制。
如果您停留在过去,请确保您满足返回值的复制省略 标准。你的功能,只有一个返回点,可以。尽管不是必需的,但任何像样的编译器都会执行该优化。
Is it possible to use boost::unique_ptr or boost::shared_ptr to handle this vector output?
是的,但这会不必要地复杂化。只需按值返回。
关于c++ - 传递 vector 引用是否会转移其数据的所有权?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26892427/