对指针和恒常性兼容性的引用

references to pointers and constness compatibility

本文关键字:兼容性 引用 常性 指针      更新时间:2023-10-16

出于学习目的,我编写了以下代码:

void Swap(const int *&Pointer1, const int *&Pointer2)
{
const int *Tmp = Pointer2;
Pointer2 = Pointer1;
Pointer1 = Tmp;
}

我对这段代码以及顶级/低级恒常性在这种情况下如何工作有一些疑问,有 3 个或更多"级别"。

  1. 显然,我的引用不能是常量,否则我将无法交换指针。但是,让我们假设代码不会触及指针值(它们包含的地址(:正确的语法是const int *(const &Pointer(或int * const &Pointer?我感觉后者意味着"引用常量指针到const int,但我不确定。如果是这种情况,编译器会忽略 const 部分,就像更简单的 const int 按值传递一样,或者不会因为它在引用下?
  2. 尝试使用指向 int 的指针调用此函数失败。但是,可以将 int 地址分配给指向 const int 的指针,如果我简单地删除引用,我确实不会出错。这让我认为这些引用"迫使"每个常量完美匹配。这是真的吗?如果是这样,有办法解决吗?
  1. 如果你也想constPointer,那么它会是int const * const & Pointer,让我们从右到左阅读它; 所以Pointer是对const指向constint的指针的引用。(请注意,这意味着Pointer本身和Pointer指向的int也无法更改。这可能会与Swap的意图相冲突。在按引用传递时,这两个const部分都不会被忽略。与按值传递不同,引用不能是顶级的const限定的,并且保留了对它所引用的内容的恒定性。

  2. 您不能将int *传递给获取const int *&的函数(即对非常量指针的左值引用(。int *可以隐式转换为const int*,但转换后的const int*是临时的,不能绑定到非常量 lvalue-reference。临时可以绑定到常量(或右值引用(的左值引用,因此将参数类型更改为int const * const & Pointer,如 #1 中所述,传递int *就可以了。

template <class P1,class P2>
void Swap(P1 && Pointer1, P2 && Pointer2)
{/*...*/}
int main()
{
const int a =1, b = 2;
Swap(&a, &b); // &a and &b - r-value, Pointer1 and Pointer2 param this 'const int* &&'
const int * const a_cref_p = &a;
const int * const b_cref_p = &b;
Swap(a_cref_p,b_cref_p); // a_cref_p and b_cref_p - l-value, Pointer1 and Pointer2 param this 'const int* const &'
const int * a_ref_p = &a;
const int * b_ref_p = &b;
Swap(a_ref_p,b_ref_p); // a_ref_p and b_ref_p - l-value, Pointer1 and Pointer2 param this 'const int* &'
return 0;
}