对指针和恒常性兼容性的引用
references to pointers and constness compatibility
出于学习目的,我编写了以下代码:
void Swap(const int *&Pointer1, const int *&Pointer2)
{
const int *Tmp = Pointer2;
Pointer2 = Pointer1;
Pointer1 = Tmp;
}
我对这段代码以及顶级/低级恒常性在这种情况下如何工作有一些疑问,有 3 个或更多"级别"。
- 显然,我的引用不能是常量,否则我将无法交换指针。但是,让我们假设代码不会触及指针值(它们包含的地址(:正确的语法是const int *(const &Pointer(或int * const &Pointer?我感觉后者意味着"引用常量指针到const int,但我不确定。如果是这种情况,编译器会忽略 const 部分,就像更简单的 const int 按值传递一样,或者不会因为它在引用下?
- 尝试使用指向 int 的指针调用此函数失败。但是,可以将 int 地址分配给指向 const int 的指针,如果我简单地删除引用,我确实不会出错。这让我认为这些引用"迫使"每个常量完美匹配。这是真的吗?如果是这样,有办法解决吗?
-
如果你也想
const
Pointer
,那么它会是int const * const & Pointer
,让我们从右到左阅读它; 所以Pointer
是对const
指向const
int
的指针的引用。(请注意,这意味着Pointer
本身和Pointer
指向的int
也无法更改。这可能会与Swap
的意图相冲突。在按引用传递时,这两个const
部分都不会被忽略。与按值传递不同,引用不能是顶级的const
限定的,并且保留了对它所引用的内容的恒定性。 -
您不能将
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;
}
相关文章:
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- 将对象数组的引用传递给函数
- 什么时候在C++中返回常量引用是个好主意
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- 何时在引用或唯一指针上使用移动语义
- 如何在c++中使用引用实现类似python的行为
- 编译C++时未定义的引用
- Ctypes wstring通过引用传递
- c++r值引用应用于函数指针
- 理解c++中的引用
- C++取消引用指针.为什么会发生变化
- 如何修复此错误:未定义对"距离(浮点数,浮点数,浮点数,浮点数,浮点数)"的引用
- 我的项目不会像"undefined reference to `grpc::g_core_codegen_interface'"那样使用未定义的引用错误进行编译
- C++Boost Asio Pool线程,带有lambda函数和传递引用变量
- 强制转换为引用类型
- 引用一个已擦除类型(void*)的指针
- 向量元素的引用地址与它所指向的向量元素的地址不同.为什么
- 对指针和恒常性兼容性的引用
- 错误:在armadillo和oracle occi兼容性问题中,对"剑"的引用不明确
- 使用按引用传递而不是按指针传递时的二进制兼容性