重新分配给常量引用

4

使用指针,我可以做到这一点:

int a=1;
int b=2;

const int* cnstIntPtr = &a;
// (*cnstIntPtr)++ does not work, makes sense since value pointed to is constant
cnstIntPtr = &b; // works, makes sense

const int* const cnstIntCnstPtr  = &a;
// (*cnstIntCnstPtr)++; does not work, makes sense since value pointed to is constant
// cnstIntCnstPtr = &b;  does not work, makes sense since pointer is constant

但需要提供参考资料:

const int& cnstIntRef = a;
// cnstIntRef++; does not work, makes sense since const refers to value at address
// cnstIntRef = b; why does this not work? "expression must be modifiable lvalue"

const int& const cnstIntCnstRef = a;
//cnstIntCnstRef++; does not work, makes sense since const refers to value at address
//cnstIntCnstRef = b; does not work, makes sense since const refers to value at address

为什么当const应该引用地址上的值时(类比指针的工作方式),我不能重新分配给const引用。如果一般情况下不可能,为什么会这样,并且const int& const cnstIntCnstRef中第二个const的含义是什么?

4
无法重新绑定引用。一旦初始化为引用某个对象,它将在其生命周期内引用该对象。const int& const cnstIntCnstRef 中的第二个 const 是多余的。 - Igor Tandetnik
就像Igor所说,当您编写"cnstIntCnstRef = b;"时,您试图更改引用的对象:被引用的东西(也称为"a")。 但是这是不允许的,因为它声明为const。 而且您绝对不允许使引用指向其他内容(比如说,"b")。 - Joe
如果您想重新分配引用,请使用 std::reference_wrapper。请注意,它主要用于通用代码和转发目的。 - Guillaume Racicot
那么我该如何处理初始化列表中的std::vector<const int&>?我需要做的是设置它的大小,并在构造函数体中填充元素。不幸的是,push_back不可行,因为它会搞乱引用。 - braaterAfrikaaner
1个回答

1
// cnstIntRef = b; why does this not work? "expression must be modifiable lvalue"
由于cnstIntRef++;不起作用的原因和以下相同:cnstIntRef是常量的引用,因此该值不可被分配。

如果通常情况下不可能,那么为什么会这样呢?

确实不可能。

引用与指针不同:它们自动取消引用。对引用变量的赋值是对所引用对象的赋值。就像你理解cnstIntRef++类似于(*cnstIntPtr)++一样,你必须也理解cnstIntRef = a类似于*cnstIntPtr = a

因此,没有语法可以“重新分配”一个引用以引用另一个对象。引用在其整个生命周期中始终只引用一个对象。


what is the meaning of the second const in

const int& const cnstIntCnstRef?

它没有意义,因为它是不规范的。与指针不同,限定符不能应用于引用; 它们只能应用于所引用的类型。


那么如何处理一个 std::vector<const int&> 呢?

你无法处理 std::vector<const int&>,因为 const int& 不是 std::vector 元素的有效类型。向量要求元素可擦除,而引用不可擦除。

我需要做的是设置它的大小,在构造函数体中填充元素。

您可以使用指针向量。或者如果出于模板目的更方便,可以使用 std::reference_wrapper 的向量。

push_back 不可行,因为它会破坏引用。

reserve 后,push_back 就不会破坏引用了。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接