引用绑定和复制构造函数/移动构造函数

Reference binding and the copy constructor/move constructor

本文关键字:构造函数 移动 复制 绑定 引用      更新时间:2023-10-16

如果我有这样的函数:

int foo(std::vector<int>* integer1ArrayIn, * integer2ArrayIn) {
    std::vector<int>& integer1Array = *integer1ArrayIn;
    std::vector<int>& integer2Array = *integer2ArrayIn;
}
  1. 引用integer1Array调用复制构造函数/移动构造函数来复制传入参数的元素吗?
  2. 将引用绑定到取消引用的指针是否会调用复制构造函数?
  3. 引用绑定在什么情况下调用复制构造函数?
  4. 有人可以解释一下此代码在内存中执行时会发生什么吗?

谢谢

  1. 不。
  2. 不,但如果它是空的,它会严重崩溃。考虑在参数必须存在时通过引用传递,并在参数可能存在时通过指针传递(但也始终验证 nullptr!
  3. 每当 l 值(在本例中为 integer1Arrayinteger2Array(是指针或引用时,它永远不会调用 copy/move 构造函数。

如果你有std::vector integer1Array = *integer1ArrayIn它会有效地制作副本。

你可以用乔纳斯的答案来玩弄,亲眼看看:)

1(不,没有制作副本。你可以用一个小程序来测试它,就像这样。

#include <iostream>
struct foo
{
    foo() { std::cout << "Constructor" << std::endl; }  
    foo(const foo&) { std::cout << "Copy constructor" << std::endl; }
    foo& operator=(const foo&) { std::cout << "Copy assignment operator" << std::endl; }    
};
int main() {
    foo* A = new foo;
    foo& B = *A;
    delete A;
}

2(小心nullptr!否则一切都很好。

3(从不(见AlexG的回答(

4(不确定"代码在内存中执行

"是什么意思,因为代码不是在内存中执行的。如果你的意思是程序执行时内存会发生什么,那就是另一回事了