为什么重新设置参考是非法/不道德的?

2023-12-02C/C++开发问题
1

本文介绍了为什么重新设置参考是非法/不道德的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

可能的重复:
为什么引用不能在 C++ 中重新安装

我正在尝试或多或少地交换两个参考变量(作为实践,我本可以交换实际变量).我尝试通过创建一个临时变量并使一个引用与另一个引用相等来做到这一点,但这被编译器拒绝了.下面是一个例子:

I am trying to more or less swap two reference variables (as practice, I could have swapped the actual variables). I tried doing this by making a temporary variable and making one of the references equal the other, but this got shot down by the compiler. Here is an example:

void Foo()
{
   //code
   int& ref1 = a;
   int& ref2 = b;
   int temp;

   temp = ref1;
   ref1 = ref2;
   ref2 = temp;

   //or, better yet
   std::swap(ref1, ref2);
}

我遇到了一个错误,并查看了 faq lite.它详细说明它们不能重新安装,但没有解释原因.为什么?

I got an error, and looked on the faq lite. It details that they cannot be reseated, but does not explain why. Why?

这里是 Faq Lite 的链接以供参考 (<;---,明白了吗?)

Here is a link to the Faq Lite for reference (<---, get it?).

推荐答案

因为没有语法可以做到:

Because there is no syntax to do it:

int x = 0;
int y = 1;
int & r = x;

现在如果我说:

r = y;

我将 y 的值赋给 x.如果我想重新安装,我需要一些特殊的语法:

I assign the value of y to x. If I wanted to reseat I would need some special syntax:

r @= y;    // maybe?

由于使用引用的主要原因是作为函数的参数和返回类型,在这不是问题的情况下,C++ 的设计者似乎并不认为这是一条值得走的路.

As the main reason for using references is as parameters and return types of functions, where this is not an issue, it didn't seem to C++'s designers that this was a path worth going down.

这篇关于为什么重新设置参考是非法/不道德的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&amp;()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6