【问题标题】:Is it possible to use reference type alias with pointer operator to declare a reference to pointer?是否可以将引用类型别名与指针运算符一起使用来声明对指针的引用?
【发布时间】:2019-12-12 23:47:06
【问题描述】:

我在这里有一个简单的例子:我使用类型别名使用using 关键字作为引用类型然后我想知道我是否可以使用该类型别名和指针运算符(*)来声明对指针的引用:

int main(){

    using ref_int = int&;

    int x = 10;
    int* p = &x;

    //int*(&rpx) = p;
    //ref_int * rptrx = p; // pointer to reference is not allowed.
    *ref_int(rptrx) = p; // rptrx is undefined

}
  • 因为好奇,当我使用 std::vector<int>::reference 的 Element-type 时,我想将它与指针运算符 * 结合起来声明对指针的引用:

    int* ptr = new int(1000);
    std::vector<int>::*(reference rptr) = ptr; // error: expected expression
    
  • 但我可以使用指针类型别名结合引用运算符“&”来声明它:

    using pInt = int*;
    
    int i = 57;
    int* ptrI = &i;
    pInt(&rpInt) = ptrI;
    
    cout << *rpInt << endl;
    

** 我知道我不能有指向引用的指针,因为引用只是已经存在的对象的别名,而指针是对象,因此我们可以拥有指针或对它的引用。

【问题讨论】:

    标签: c++ pointers reference type-alias


    【解决方案1】:

    在 C++ 中不能有指向引用的指针。在 C++ 中,引用只是它们所引用事物的别名,标准甚至不要求它们占用任何存储空间。尝试使用引用别名来引用指针是行不通的,因为使用别名只会给你一个指向引用类型的指针。

    所以,如果你想要一个指向引用所指事物的指针,你只需使用

    auto * ptr = &reference_to_thing;
    

    如果你想要一个指针的引用,语法是

    int foo = 42;
    int* ptr = &foo;
    int*& ptr_ref = ptr;
    

    【讨论】:

    • “我想将引用类型别名与指针运算符结合起来声明对指针的引用,而不是相反”。这是我的问题。无论如何,谢谢。
    • @Maestro 我已经更新了答案以解释为什么不能使用引用别名来构建对指针的引用。
    猜你喜欢
    • 1970-01-01
    • 2012-01-30
    • 2016-12-01
    • 2022-11-11
    • 2011-05-14
    • 2021-06-08
    • 1970-01-01
    • 2019-10-06
    • 2012-07-23
    相关资源
    最近更新 更多