在c++中,当我将引用的值赋给对象时会发生什么?

What happens when I assign an object the value of a reference in C++?

本文关键字:对象 什么 c++ 引用      更新时间:2023-10-16
#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;
}

因此,函数test从我的main函数接收到对字符串s的引用。

我的问题是,这一行是做什么的:

std::string p = s;

是否浅层复制引用并将其放在p中,从而违背了最初使用引用的目的?

或者它(p)只是作为一个参考?

它创建了引用值的副本,它不允许您用p编辑s的内容,为了使p作为引用并能够从p编辑s,您必须将其声明为引用:

std::string& p = s;

因此违背了最初使用引用的目的?

为什么它违背了引用的目的,你已经声明了s作为引用,不是吗?不是p。如前所述,它将复制s包含的值

当我在c++中给一个对象赋值时,会发生什么?

不能给引用赋值,或者至少不应该这样考虑。引用不是指针。因为引用是通过不同的名称访问的对象,所以给对象赋值。

void test(std::string &s) {

处理引用的事实只在声明点真正相关。该函数中所有使用s的代码都使用std::string,而不是std::string &

我的问题是,这一行是做什么的:

std::string p = s;

它将你的std::string对象赋值给p,不多也不少。换句话说,它的作用与下面程序中的相同:

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;
}

或者更简单地说:

int main() {
   std::string s = "Hello world";
   std::string p = s;
   std::cout << p.length() << " " << p;
}
相关文章: