如果我将"reference to vector"分配给"vector"会发生什么情况
what happens if I assign "reference to vector" to "vector"
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();
相关文章:
- 将指针分配给另一个指针时会发生什么情况?
- 在什么情况下,两个堆栈分配的结构对象的 this 点指向同一个地址?
- 在什么情况下,我想在 C/C++ 代码中使用内联汇编代码
- 发生注入类名时会发生什么情况?(C++)
- 在什么情况下,需要共享智能指针而无法使用唯一指针?
- 重新分配向量时,向量中的内存会发生什么情况
- 如果结构中的字符串比使用的 p/调用签名长或短,会发生什么情况?
- 为什么或在什么情况下,你会将参数作为C++中的引用(或指针)传递给函数?
- 如果我向一个12字节的缓冲区写入的字节数少于12,会发生什么情况
- 删除对象(具有不同类型)的引用时会发生什么情况?
- 如果我在 c++ 中以 new 的放置形式使用没有足够的内存,会发生什么情况?
- 使用 Google 基准测试时返回值会发生什么情况?
- 正在连接的等待条件变量的线程会发生什么情况?
- 如果未定义的C++行为符合 C 定义的行为,会发生什么情况?
- 在什么情况下,使用'const T*'输入参数比'const T&'更可取?
- 如果字符串在 C/C++ 中没有 NUL 字符(以防编译器允许它通过)会发生什么情况?
- 将虚拟方法定义为私有方法时会发生什么情况?
- 当我们push_back元素时,std::vector 什么时候会放大自己?
- 如果我将"reference to vector"分配给"vector"会发生什么情况
- 在 vector 的复制/移动分配下,底层存储会发生什么情况?