[英]What happens when I assign an object the value of a reference in C++?
#include <iostream>
void test(std::string &s) {
std::string p = s;
std::cout << p.length() << " " << p;
}
int main() {
std::string s = "Hello world";
test(s);
return 0;
}
So, the function test
receives a reference to my string s
from my main
function. 因此,功能
test
从我的main
功能接收到对我的字符串s
的引用。
My question is, what does this line do: 我的问题是,这行代码做什么:
std::string p = s;
Does it shallow copy the reference and put it in p
, thereby defeating the purpose of using a reference in the first place? 它是否浅复制了引用并将其放在
p
,从而违反了首先使用引用的目的?
Or does it ( p
) just act as a reference? 还是(
p
)只是作为参考?
它创建引用的值的副本,不允许您使用p
编辑s
的内容,以使p
充当引用并能够从p
编辑s
,您必须将其声明为引用:
std::string& p = s;
thereby defeating the purpose of using a reference in the first place?
从而打败了首先使用引用的目的?
Why does it defeat the purpose of reference, you have declared s
as reference, isn't it? 您为什么将
s
声明为引用,为什么它违反引用的目的,不是吗? Not p
. 不是
p
。 So as noted indeed it will copy the value which s
contains. 因此确实如前所述,它将复制
s
包含的值。
What happens when I assign an object the value of a reference in C++?
在C ++中为对象分配引用的值时会发生什么?
You cannot assign the value of a reference, or at least you should not think in such terms. 您无法分配参考的价值,或者至少您不应该这样考虑。 A reference is not a pointer.
引用不是指针。 What happens is that you assign the value of an object, because a reference is the object , accessed via a different name.
发生的情况是您分配了一个对象的值,因为引用是通过不同名称访问的对象 。
void test(std::string &s) {
The fact that you are dealing with a reference is only really relevant at the point of declaration. 您正在处理引用的事实仅在声明时才有意义。 All code in this function which uses
s
uses a std::string
, not a std::string &
. 此函数中所有使用
s
代码都使用std::string
,而不是std::string &
。
My question is, what does this line do:
我的问题是,这行代码做什么:
std::string p = s;
It assigns your std::string
object to p
, no more, no less. 它将您的
std::string
对象分配给p
,不多也不少。 In other words, it does the same as it would in this program: 换句话说,它的作用与该程序相同:
int main() {
std::string s = "Hello world";
std::string &s_with_different_name = s;
std::string p = s_with_different_name;
std::cout << p.length() << " " << p;
}
Or, even more simply, in this: 或者,更简单地说,是这样的:
int main() {
std::string s = "Hello world";
std::string p = s;
std::cout << p.length() << " " << p;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.