如果我将"reference to vector"分配给"vector"会发生什么情况

what happens if I assign "reference to vector" to "vector"

本文关键字:vector 什么情况 分配 reference to 如果      更新时间:2023-10-16

Friends 我碰巧错误地编写了这段代码:

const std::vector<int> &FunctionReturnReferenceToVector();
vector<int> tmp;
/*do something else*/
tmp = FunctionReturnReferenceToVector();

编译器没有抱怨,我的程序以正确的结果成功结束。

请问整个过程到底发生了什么?

我使用CLion IDE和Clang作为编译器。

如果您查看std::vector<>的赋值运算符(以及复制构造函数(,您会发现没有一个按值获取另一个vector<>运算符。

无论如何,它们都是通过引用传递的(然后由复制构造函数复制,这就是为什么它被称为复制构造函数(。

参考通常与"真实的东西"一样好。只要向量FunctionReturnReferenceToVector()返回的引用仍然存在,一切都很好......

仍然存在,是吗?如果它只存在于该函数的本地,你就有麻烦了。;-)

tmp将成为返回的向量内容的副本。在这种情况下,FunctionReturnReferenceToVector返回向量这一事实无关紧要,因为您的代码正在调用复制赋值运算符。

您的向量将被复制。tmp将是引用所引用的向量的副本。您可以在自己有趣的示例中看到此行为。喜欢这个:

struct Copy {
Copy(int in) : _i(in) {}
// Copy assignment, just like std::vector!
Copy& operator=(const Copy& copy) {
_i = copy._i;
std::cout << "I was Copied!n";
}
int _i;
};
Copy a(3), b(5), &c = b;
a = c;

而输出,你能猜到吗:

我被复制了!

现场示例

从您的问题中不清楚对向量的引用来自哪里。我假设它是从函数返回的:

const std::vector<int> &FunctionReturnReferenceToVector();

在这种情况下,tmp = FunctionReturnReferenceToVector()只是使用赋值运算符std::vector<int>::operator=(const std::vector<int>&)将向量复制到变量tmp

要使用原始向量进行操作,您可以将 const 引用分配给返回的向量:

const auto &tmp = FunctionReturnReferenceToVector();
相关文章: