【问题标题】:using reference pointer type as Paramter in c++在c ++中使用引用指针类型作为参数
【发布时间】:2021-08-23 18:32:39
【问题描述】:

当我使用引用指针类型作为参数时遇到了一些问题。

首先,这是我的代码。

#include<iostream>
using namespace std;

void test(int*& ptr);

int main(void)
{
int* ptr = new int[1];
ptr[0] = 100;
cout << ptr[0];

test(ptr);
cout << ptr[0] << '\t' << ptr[1];
}

void test(int*& ptr)
{
int* tmp = new int[2];
tmp[0] = 1;
tmp[1] = 2;

int* tmp2 = ptr;
ptr = tmp;
cout << ptr[0] << '\t' << ptr[1];
delete[]tmp2;
}

当编译这段代码时,输​​出是

100
1       2

这个输出是我想要得到的

但是当我调试这段代码时,

Exception thrown: read access violation.

发生了这个错误。

如何避免这个错误,我的错是什么? :(

如果不使用引用类型重新分配参数的内存,我该怎么办?

【问题讨论】:

  • 引用类型不是问题;对动态内存管理和指针 is 的基本和基本了解。例如:delete[]ptr; 破坏了你刚刚分配的内存。回到main,您现在有一个悬空指针。您还泄漏了在main 中分配的原始内存。无关,tmp2 毫无价值,可以说tmp 也是如此。
  • 传递的ptr中的单个项目,访问ptr[1]表示第二个项目
  • 哦,对不起,我修复了我的代码...
  • 我想知道的是,当我调用一个有参数的函数(内存分配的指针(引用类型))时,我可以更改参数(指针)在函数中指向的地址吗..

标签: c++ pointers reference


【解决方案1】:

参考不是问题。是你的动态内存管理被严重破坏了。


#include <iostream>
using namespace std;

void test(int *&ptr);

int main(void)
{
    int *ptr = new int[1]; // allocates a sequence of 1
    ptr[0] = 100;
    cout << ptr[0];

    test(ptr); // sends pointer to sequence by reference to test
    cout << ptr[0] << '\t' << ptr[1];
}

void test(int *&ptr)
{
    int *tmp = new int[2]; // allocates a sequence of size 2
    tmp[0] = 1;
    tmp[1] = 2;

    int *tmp2 = ptr; // stores original passed-in pointer to tmp2
    ptr = tmp; // assigns new sequence pointer to reference argument (leaks original)
    cout << ptr[0] << '\t' << ptr[1];

    delete[] ptr; // deletes the new sequence. (leaves dangling pointer)
}

你似乎在试图做的是:

#include <iostream>
using namespace std;

void test(int *&ptr);

int main(void)
{
    int *ptr = new int[1];
    ptr[0] = 100;
    cout << ptr[0] << '\n';

    test(ptr);
    cout << ptr[0] << '\t' << ptr[1] << '\n';
    delete [] ptr;
}

void test(int *&ptr)
{
    delete [] ptr;    // delete original sequence
    ptr = new int[2]; // create new sequence
    ptr[0] = 1;
    ptr[1] = 2;
}

停止使用原始指针

或者,使用智能指针来管理它。

#include <iostream>
#include <memory>
using namespace std;

void test(std::unique_ptr<int[]>& ptr);

int main(void)
{
    std::unique_ptr<int[]> ptr = std::make_unique<int[]>(1);
    ptr[0] = 100;
    cout << ptr[0] << '\n';

    test(ptr);
    cout << ptr[0] << '\t' << ptr[1] << '\n';
}

void test(std::unique_ptr<int[]>& ptr)
{
    ptr = std::make_unique<int[]>(2);
    ptr[0] = 1;
    ptr[1] = 2;
}

或者更好的是,只需使用std::vector&lt;int&gt;

【讨论】:

  • 感谢您的回答,但是,我可以再次使用已删除的指针吗?
  • 当我删除内存分配时,内存中发生了什么?被删除的指针是指向NULL还是垃圾值?
  • 比,我可以随时使用已删除的指针并确保避免悬空指针吗?
  • stackoverflow.com/questions/28379457/… 哦,我找到了我的问题的答案!谢谢!
猜你喜欢
  • 1970-01-01
  • 2010-12-16
  • 2018-05-18
  • 1970-01-01
  • 2012-12-07
  • 2011-02-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多