英文:
Pointer to rvalue reference illegal?
问题
int* p = &r; // 这是指向引用的指针
英文:
Consider the following code:
#include <iostream>
int main() {
int a1 = 1;
int a2 = 2;
int&& r = a1 + a2; // rvalue reference
r++;
std::cout << r << std::endl;
int* p = &r; // what is this if not pointer to reference?
std::cout << &r << " " << p << " " << *p << std::endl;
*p++;
std::cout << &r << " " << p << " " << *p << std::endl;
}
cppreference.com claims:
> Because references are not objects, there are no arrays of references,
> no pointers to references, and no references to references
However what is int* p = &r
if not a pointer to reference?
答案1
得分: 1
你在这里误解了并混淆了两个不同的概念 - 一个是对象的类型,另一个是该对象的值。在这行代码中:
int *p = &r;
你定义了 p
的类型为 指向整数的指针
,在C++中没有办法声明/定义类型为 指向整数引用的指针
,这是cppreference.com的意思。
它所持有的值是引用 r
所指向的对象在内存中的地址,但对该语句来说并不相关。
英文:
You misunderstand and mixed 2 separate concepts here - one is the type of an object and another is the value of that object. In this line:
int *p = &r;
you define p
to have type pointer to int
and there is no way in C++ to declare/define a type pointer to reference to int
which what cppreference.com means.
Value it holds is an address of object in memory to which reference r
refers, but it is irrelevant though to that statement.
答案2
得分: 1
> 但int* p = &r
实际上是一个指向int
的指针,而不是一个指向引用的指针。它指向引用所指向的内容,而不是引用本身。
指向引用的指针应该是int &*
,但这是无法编译通过的。
英文:
> However what is int* p = &r if not a pointer to reference?
It's a pointer to int
. That is, int *
. It points to whatever the reference points to, not to the reference itself.
A pointer to reference would be int &*
- and this doesn't compile.
You can also test it like this:
#include <iostream>
template <typename T>
void PrintType()
{
std::cout <<
#ifdef _MSC_VER
__FUNCSIG__
#else
__PRETTY_FUNCTION__
#endif
<< '\n';
}
Then PrintType<decltype(&r)>()
prints something like void PrintType() [T = int *]
. Note, no &
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论