本文介绍了为什么const char * const& ="hello"编译?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从一本书中阅读一个代码片段,并找到了它:

I am reading a code snippet from a book and find this:

const char* const & a = "hello"; //can compile
const char*& a = "hello"; //cannot

我所知道的是,初始化引用时,不会发生指向指针转换的数组.

All I know is that when initializing a reference, the array to pointer conversion would not take place.

const char* const &,对const pointer的引用,指针指向const char.

const char* const &, a reference to a const pointer, the pointer points to const char.

const char*&,对pointer的引用,指针指向const char.

const char*&, a reference to a pointer, the pointer points toconst char.

那么为什么要添加一个额外的const来指示该指针是const,允许它进行编译?

So why does adding an extra const, indicating that the pointer is a const, allow it to compile?

推荐答案

它本质上是遵循此公式的

It's essentially adhering to this formula

T const & a = something_convertible_to_T;

其中T是const char*.在第一种情况下,可以实现一个临时指针,为其分配文字的地址,然后将其自身绑定到该引用.在第二种情况下,由于左值引用不是const,因此不会发生.另一个例子更多

Where T is const char*. In the first case, a temporary pointer can be materialized, assigned the address of the literal, and then have itself bound to the reference. In the second case, since the lvalue reference isn't const, it can't happen. Another example of more of the same

const char* && a = "hello"; // rvalue ref makes a no into a yes.

现在,临时指针已绑定到右值引用.

Now the temporary pointer is bound to an rvalue reference.

这篇关于为什么const char * const& ="hello"编译?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 07:39