gpt4 book ai didi

c++ - 当我们将引用分配给变量时会发生什么?

转载 作者:行者123 更新时间:2023-12-01 23:00:34 25 4
gpt4 key购买 nike

void func(){
int a = 1;
int b = a; // copy assignemnt
int &c = a; // nothing?
int d = c; // nothing?
}

例如,当我们将引用c赋值给d时,是否有任何触发(移动、复制等)?

如果 d 是实例成员怎么办?将局部变量引用存储到其中是否安全?

最佳答案

when we assign reference c to d, is there anything triggered (move, copy, etc.)?

你的术语让我感到困惑!如果您在谈论 dc,我假设您指的是 int d = c; 我将其描述为“分配任何 c 指的是 d”。 “将引用 c 分配给 d”听起来太像 int& c = d;

您的代码有:

int &c = a; // nothing?
int d = c; // nothing?

在第一行中,没有任何你需要关心的事情发生...... c 可以被认为是 a 的昵称或别名。 (在隐藏的实现级别,将 c 想象成一个自动取消引用的指针变量,并且您的 int &c = a; 类似于 int* p_c = &a; - 它不会复制或移动任何 int 值,也不会以任何方式更改 a。)

在第二行中,变量 d 被赋予了 a 值的拷贝。

What if d is an instance member? Is it safe to store a local variable reference into it?

您的想法是错误的。当您分配给成员引用时,您是在分配给引用的对象,而不是引用本身。引用的对象将是某个地方的另一个 int,并且从一个 int 到另一个的赋值照常进行。

关于c++ - 当我们将引用分配给变量时会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71863108/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com