指向右值引用的指针是非法的吗?

huangapple go评论62阅读模式
英文:

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 &.

huangapple
  • 本文由 发表于 2023年4月11日 01:41:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/75979379.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定