【问题标题】:What is the difference between * and *& in C++? [duplicate]C++中的*和*&有什么区别? [复制]
【发布时间】:2014-09-03 07:51:05
【问题描述】:

函数参数中的 * 和 *& 有什么区别。例如,

这有什么区别,

void a(SomeType *s)
{

}

还有这个,

void a(SomeType *&s)
{

}

【问题讨论】:

  • intint &有什么区别?
  • void a(SomeType *s):按值传递指针svoid a(SomeType *&s):通过引用传递指针s
  • @chris: 我应该在哪里使用 * 和 *&?
  • @user3335,决定与int vs int &相同。

标签: c++


【解决方案1】:

当您将引用(使用&)传递给函数时,您可以修改值并且修改不会是本地的。如果您不传递引用(没有&),则修改将是函数的本地。

#include <cstdio>
int one = 1, two = 2;

// x is a pointer passed *by value*, so changes are local
void f1(int *x) { x = &two; }

// x is a pointer passed *by reference*, so changes are propagated
void f2(int *&x) { x = &two; }

int main()
{
    int *ptr = &one;
    std::printf("*ptr = %d\n", *ptr);
    f1(ptr);
    std::printf("*ptr = %d\n", *ptr);
    f2(ptr);
    std::printf("*ptr = %d\n", *ptr);
    return 0;
}

输出:

*ptr = 1 *ptr = 1 *ptr = 2

【讨论】:

    【解决方案2】:

    首先,让我们给a添加一些“肉”:

    void a1(SomeType *s)
    {
        s = new SomeType;
    }
    
    void a2(SomeType *&s)
    {
        s = new SomeType;
    }
    

    现在假设你有这个代码,它调用a

    void func()
    {
        SomeType *p1 = nullptr;
        a1(p1);
        if (p == nullptr)
            std::cout << "p1 is null" << std::endl;
        else
            std::cout << "p1 is not null" << std::endl;
    
        SomeType *p2 = nullptr;
        a2(p2);
        if (p == nullptr)
            std::cout << "p2 is null" << std::endl;
        else
            std::cout << "p2 is not null" << std::endl;
    }
    

    a1 接受一个指针,因此变量s 是一个指针的副本 p1。所以当a 返回时,p1 仍然是nullptr 并且在a1 内部分配的内存泄漏。

    a2 接受对指针的引用,因此sp2 的“别名”。所以当a2返回p2指向a2内部分配的内存。

    一般情况下,请参阅What's the difference between passing by reference vs. passing by value?。然后将这些知识应用于指针。

    【讨论】:

      【解决方案3】:

      在第一种情况下,函数接受指针的值。在第二种情况下,该函数接受对指针变量的非常量引用,这意味着您可以通过引用更改此指针位置。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-11-01
        • 2023-04-08
        • 2018-07-18
        • 2013-05-23
        • 2011-07-15
        • 2017-04-18
        • 2011-08-06
        • 1970-01-01
        相关资源
        最近更新 更多