-5

我只是想知道以上两者之间的区别。由于指针传递引用特性,是否有所谓的动态内存分配?

4

2 回答 2

1

Those two are two different things.

In C++, pass by reference is done by adding & to the parameter in a function:

void func(&a) {
   a = 5;
}

int main() {
    int a = 0;
    printf("%d", a);
    func(a);
    printf("%d", a);
    return 0;
}

The above code will pass the reference of variable a to func(). This cause the value of variable a within the main() method to change as well.

Dynamic memory allocation is another thing. It is done as follows:

int* arr;
arr = new int[n];

where n will be determined in the runtime. The memory you allocate dynamically as above should be deallocated by yourself to avoid memory leaks.

于 2018-06-12T05:07:16.863 回答
-1

您真正感兴趣的对比是按引用传递和按指针传递之间的对比。

void f(int* ip) {
    ++*ip;
}

void g(int& ir) {
    ++ir;
}

int main() {
    int i = 0;
    f(&i);
    std::cout << i << '\n'; // i is 1
    g(i);
    std::cout << i << '\n'; // i is 2
    return 0;
}

回到过去(当我们都用 C 编写代码时)没有引用,所以如果你想能够创建一个对象,将它传递给一个函数,并让该函数修改对象,你必须传递该对象的地址。在函数内部,您取消引用指针,这使您可以修改传入的对象。这就是函数的f作用。

在 C++ 中,我们通过引用传递。这使您可以使用对象本身调用函数,而无需获取地址;并且在函数中,不需要取消引用指针。这就是函数的g作用。

这两种方法都适用于您在堆栈上创建的对象和您使用动态分配创建的对象,即使用new. 以前的版本使用堆栈上的对象。这是一个使用创建的对象new

int main() {
    int *ii = new int(0);
    f(ii);
    std::cout << *ii << '\n'; // ii is 1
    g(*ii);
    std::cout << *ii << '\n'; // ii is 2
    delete ii;
    return 0;
}
于 2018-06-12T05:29:48.583 回答