C ++从函数返回指向数组的指针的正确方法 [英] C++ correct way to return pointer to array from function

查看:29
本文介绍了C ++从函数返回指向数组的指针的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 C++ 相当陌生,并且一直在避免使用指针.从我在线阅读的内容来看,我无法返回数组,但可以返回指向它的指针.我编写了一个小代码来测试它,并想知道这是否是执行此操作的正常/正确方法:

I am fairly new to C++ and have been avoiding pointers. From what I've read online I cannot return an array but I can return a pointer to it. I made a small code to test it and was wondering if this was the normal / correct way to do this:

#include <iostream>
using namespace std;

int* test (int in[5]) {
    int* out = in;
    return out;
}

int main() {
    int arr[5] = {1, 2, 3, 4, 5};
    int* pArr = test(arr);
    for (int i = 0; i < 5; i++) cout<<pArr[i]<<endl;
    cout<<endl;
    return 0;
}


编辑:这似乎不好.我应该如何重写它?


Edit: This seems to be no good. How should I rewrite it?

int* test (int a[5], int b[5]) {
    int c[5];
    for (int i = 0; i < 5; i++) c[i] = a[i]+b[i];
    int* out = c;
    return out;
}

推荐答案

您的代码目前是正确的,但我很难弄清楚它可以/将如何用于现实世界的场景.话虽如此,从函数返回指针时请注意一些注意事项:

Your code as it stands is correct but I am having a hard time figuring out how it could/would be used in a real world scenario. With that said, please be aware of a few caveats when returning pointers from functions:

  • 当你使用语法 int arr[5]; 创建一个数组时,它被分配在堆栈上并且对于函数来说是本地的.
  • C++ 允许您返回指向此数组的指针,但在其本地范围之外使用此指针指向的内存是未定义行为.阅读使用现实世界的类比的好答案 获得比我无法解释的更清晰的理解.
  • 如果你能保证数组的内存没有被清除,你仍然可以在作用域之外使用数组.在您的情况下,当您将 arr 传递给 test() 时,这是正确的.
  • 如果你想传递指向动态分配数组的指针而不用担心内存泄漏,你应该阅读std::unique_ptr/std::shared_ptr<>.
  • When you create an array with syntax int arr[5];, it's allocated on the stack and is local to the function.
  • C++ allows you to return a pointer to this array, but it is undefined behavior to use the memory pointed to by this pointer outside of its local scope. Read this great answer using a real world analogy to get a much clear understanding than what I could ever explain.
  • You can still use the array outside the scope if you can guarantee that memory of the array has not be purged. In your case this is true when you pass arr to test().
  • If you want to pass around pointers to a dynamically allocated array without worrying about memory leaks, you should do some reading on std::unique_ptr/std::shared_ptr<>.

编辑 - 回答矩阵乘法的用例

您有两个选择.最简单的方法是使用 std::unique_ptr/std::shared_ptr<>.现代 C++ 方法是拥有一个 Matrix 类,您可以在其中重载 operator * 并且如果您想避免,您绝对必须使用新的 rvalue 引用复制乘法的结果以将其从函数中取出.除了拥有你的copy constructoroperator =destructor,你还需要有move constructor 和<代码>移动赋值运算符.浏览此搜索的问题和答案,以更深入地了解如何实现这一目标.

You have two options. The naive way is to use std::unique_ptr/std::shared_ptr<>. The Modern C++ way is to have a Matrix class where you overload operator * and you absolutely must use the new rvalue references if you want to avoid copying the result of the multiplication to get it out of the function. In addition to having your copy constructor, operator = and destructor, you also need to have move constructor and move assignment operator. Go through the questions and answers of this search to gain more insight on how to achieve this.

编辑 2 - 对附加问题的回答

int* test (int a[5], int b[5]) {
    int *c = new int[5];
    for (int i = 0; i < 5; i++) c[i] = a[i]+b[i];
    return c;
}

如果您将其用作 int *res = test(a,b);,那么稍后在您的代码中,您应该调用 delete []res 来释放 test() 函数中分配的内存.您现在看到的问题是,很难手动跟踪何时调用 delete.因此,答案中概述了如何处理它的方法.

If you are using this as int *res = test(a,b);, then sometime later in your code, you should call delete []res to free the memory allocated in the test() function. You see now the problem is it is extremely hard to manually keep track of when to make the call to delete. Hence the approaches on how to deal with it where outlined in the answer.

这篇关于C ++从函数返回指向数组的指针的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆