为什么可以为引用分配新值,以及如何使引用引用其他内容?

发布于 2024-12-01 09:24:55 字数 829 浏览 0 评论 0 原文

我有几个与 C++ 中引用的使用相关的问题。

  1. 在下面所示的代码中,它是如何工作的并且在 q = "world"; 行没有给出错误?

    #include ;
    
    使用命名空间 std;
    
    int main()
    {
      char *p = "你好";
      char* &q = p;
      cout <

    1. 如何将引用 q 重新初始化为其他内容?

    2. 字符串文字 p = "Hello" 不是常量还是在只读空间中?所以如果我们这样做,

      q = "世界";
      

      p处应该是常量的字符串不会被改变吗?

  2. 我读过有关 C++ 引用类型变量的内容,因为它们无法重新初始化或重新分配,因为它们在“内部”存储为常量指针。所以编译器会给出错误。

    但是实际上如何重新分配引用变量呢?

    int i;
    
    int & j = i;
    
    整数 k;
    
    j=k; //这应该没问题,但是我们如何重新分配给其他东西以使编译器标记错误?
    

    我正在尝试获取此引用,并且可能错过了一些相关的关键内容,因此这些问题。

因此,任何能够解决这个问题的指示都会很有用。

I have couple of questions related to usage of references in C++.

  1. In the code shown below, how does it work and not give a error at line q = "world";?

    #include <iostream>
    
    using namespace std;
    
    int main()
    {
      char *p = "Hello";
      char* &q = p;
      cout <<p <<' '<<q <<"\n";
      q = "World"; //Why is there no error on this line
      cout <<p <<' '<<q <<"\n";
    }
    
    1. How can a reference q be reinitialized to something else?

    2. Isn't the string literal, p = "Hello", a constant or in read-only space? So if we do,

      q = "World";
      

      wouldn't the string at p which is supposed to be constant be changed?

  2. I have read about C++ reference type variables as they cannot be reinitialized or reassigned, since they are stored 'internally' as constant pointers. So a compiler would give a error.

    But how actually a reference variable can be reassigned?

    int i;
    
    int &j = i;
    
    int k;
    
    j = k; //This should be fine, but how we reassign to something else to make compiler flag an error?
    

    I am trying to get hold of this reference, and in that maybe missed some key things related, so these questions.

So any pointers to clear this up, would be useful.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

甜味拾荒者 2024-12-08 09:24:55
    • a) 不能,您引用的行不会更改引用 q,而是更改 p
    • b) 不,文字是常量,但 p 是指向文字的指针。
      指针可以改变,但所指向的内容不能改变。
      q = "world"; 使指针 p 指向其他内容。
  1. 你似乎认为这段代码

    int i;
    int & j = i;
    整数 k;
    j=k;
    

    正在重新分配引用,但事实并非如此。
    它将k的值分配给ij仍然引用i
    我猜这是您的主要误解。

    • a) It cannot, the line you quote doesn't change the reference q, it changes p.
    • b) No the literal is constant, but p is a pointer which points at a literal.
      The pointer can be changed, what is being pointed to cannot.
      q = "world"; makes the pointer p point to something else.
  1. You seem to think that this code

    int i;
    int &j = i;
    int k;
    j = k;
    

    is reassigning a reference, but it isn't.
    It's assigning the value of k to i, j still refers to i.
    I would guess that this is your major misunderstanding.

征棹 2024-12-08 09:24:55

我认为您缺少的关于引用的一个重要细节是,一旦引用绑定到对象,您就永远无法重新分配它。从那时起,任何时候使用引用,都与使用它所引用的对象没有区别。例如,在您的第一段代码中,当您编写

q = "World";

由于 q 是绑定到 p 的引用时,这相当于编写

p = "World";

Which justchanges where p 指向的是,而不是它所指向的字符串的内容。 (这也解释了为什么它不会崩溃!)

至于你的第二个问题,一旦绑定到对象,引用就不能重新分配。如果您需要一个可以更改其所指对象的引用,则应该使用指针。

希望这有帮助!

An important detail about references that I think you're missing is that once the reference is bound to an object, you can never reassign it. From that point forward, any time you use the reference, it's indistinguishable from using the object it refers to. As an example, in your first piece of code, when you write

q = "World";

Since q is a reference bound to p, this is equivalent to writing

p = "World";

Which just changes where p is pointing, not the contents of the string it's pointing at. (This also explains why it doesn't crash!)

As for your second question, references cannot be reassigned once bound to an object. If you need to have a reference that can change its referent, you should be using a pointer instead.

Hope this helps!

巷雨优美回忆 2024-12-08 09:24:55

需要注意的是,从 C++20 开始,可以使用 placement new 来更改类内引用变量所持有的引用 code>,如下例取自这篇文章

struct C {
  int& i; // <= a reference field
  void foo(const C& other) {
    if ( this != &other ) {
      this->~C();
      new (this) C(other); // valid since C++20 even on a class 
                           // with a reference field
    }
  }
};

int main() {
    int a = 3, b = 5;
    C c1 {.i = a};
    C c2 {.i = b};
    c1.foo(c2); // the inner reference field i inside c1
                // was referring to a and now refers to b!
}

代码:http://coliru.stacked-crooked.com/a/4674071ea82ba31b

It is to be noted that since C++20, it is possible to change the reference held by a reference variable inside a class, using placement new, like in the following example taken from this SO post:

struct C {
  int& i; // <= a reference field
  void foo(const C& other) {
    if ( this != &other ) {
      this->~C();
      new (this) C(other); // valid since C++20 even on a class 
                           // with a reference field
    }
  }
};

int main() {
    int a = 3, b = 5;
    C c1 {.i = a};
    C c2 {.i = b};
    c1.foo(c2); // the inner reference field i inside c1
                // was referring to a and now refers to b!
}

Code: http://coliru.stacked-crooked.com/a/4674071ea82ba31b

や莫失莫忘 2024-12-08 09:24:55

a) 引用 q 如何重新初始化为其他内容?

不可能!

引用变量仍然是创建时初始化的别名。


b) 字符串文字 p = "Hello" 不是一个常量/只读空间吗?所以如果我们这样做,
不,不是。

char* &q = p;

这里 q 是对 char p 类型指针的引用。这里的字符串是常量,而指针不是,它可以指向另一个字符串,并且引用是该指针的别名而不是字符串文字,因此它是有效的。


c) 我的第二个问题是我读过有关 C++ 引用类型变量的内容,因为它们不能重新初始化/重新分配,因为它们在“内部”存储为常量指针。因此编译器会给出错误。

int i;

int &j = i;

int k;

j = k; //This should be fine, but how we reassign to something else to make compiler flag an error

不重新分配引用。它改变了它作为别名的变量的值。

在本例中,它将 i 的值更改为 k

a) How can a reference q be reinitialized to something else?

It cannot be!

An reference variable remains an alias to which it was initialized at time of creation.


b)Isn't the string literal, p = "Hello", a constant/in read only space. So if we do,
No it doesn't.

char* &q = p;

Here q is an reference to pointer of the type char p. The string here is constant put the pointer is not, it can be pointed to another string, and the reference is alias to this pointer not the string literal so it is valid.


c) Second question I have is I have read about C++ reference type variables as they cannot be reinitialized/reassigned, since they are stored 'internally' as constant pointers. So a compiler would give a error.

int i;

int &j = i;

int k;

j = k; //This should be fine, but how we reassign to something else to make compiler flag an error

Does not reassign the reference. it changes the value of the variable to which it was alias.

In this case it changes the value of i to k

与往事干杯 2024-12-08 09:24:55

将引用视为别名,我希望引用的世界会更容易理解。

int p; // Declares p as an integer; Defines p & allocates space
int &q = p ; // Declares a Reference. Though they are symbolically 2 variables,
             // they essentially refer to same name and same memory location.

因此,p = 5 和 q = 5 将完全相同。

在你的例子中,

char *p = "Hello"; // Declares your pointer to "Hello". p has its own existence.
char* &q = p;  // This now creates a reference (alias) to p with name q.

总而言之,p & q 是实体/对象(内存)的名称。

所以,如果你给 q 分配一些东西,它也会反映在 p 中。因为它与 p 的分配相同。
所以 q =“World”,意味着 p 现在也指向“World”。即 p & 的内存位置q 都指 - 保存“World”第一个字符的地址。

我希望如果您理解引用作为别名的概念,就不需要回答第二个问题。

Treat reference as an alias name and I hope the world of reference will much easier to understand.

int p; // Declares p as an integer; Defines p & allocates space
int &q = p ; // Declares a Reference. Though they are symbolically 2 variables,
             // they essentially refer to same name and same memory location.

So, p = 5 and q = 5 will be all the same.

In your example,

char *p = "Hello"; // Declares your pointer to "Hello". p has its own existence.
char* &q = p;  // This now creates a reference (alias) to p with name q.

So all in all, p & q are names of the entity/object (memory).

So, if you assign q something, it reflects in p too. Coz it is same as the assignment to p.
So q = "World", means p too now points to "World". i.e. the Memory location which p & q both refer to - holds the address of first character of "World".

I hope the second question need not be answered if you understand the notion of reference as an alias.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文