将智能指针传递给函数

时间:2015-10-30 16:42:16

标签: c++ pointers smart-pointers

我有一个二维智能指针数组的双打。我可以为它赋值,并显示它,但我无法将它传递给一个以双**作为输入的函数。一个简单的get()不起作用。

#include <iostream>
#include <memory>
using namespace std;
# define DIM1 3
# define DIM2 4

void funcCall(double** item)
{
    cout<< "Test function.";
}

int main() {

    std::unique_ptr<std::unique_ptr<double[]>> myArray(new std::unique_ptr<double[]>[DIM1]);

    for (int i = 0; i < DIM1; i++)
    {
        myArray.get()[i].reset(new double[DIM2]);
    }

    std::cout<<"Assign values"<<std::endl;
    for (int i = 0; i < DIM2; i++)
    {
        for (int j = 0; j < DIM1; j++)
        {
            myArray.get()[j][i] = (j+1)*(i+1);
        }
    }

    funcCall(myArray.get());    

    return 0;
}

当我编译它时,我得到:

error: cannot convert 'std::unique_ptr<std::unique_ptr<double []> >::pointer {aka std::unique_ptr<double []>*}' to 'double**' for argument '1' to 'void funcCall(double**)'  funcCall(myArray.get())

2 个答案:

答案 0 :(得分:0)

呼叫类型和功能标头不匹配。您不能将unique_ptr视为常规指针。

一种解决方案是将您的功能定义更改为:

void funcCall(std::unique_ptr<double[]> *item)

答案 1 :(得分:0)

void funcCall(std::unique_ptr<std::unique_ptr<double[]>> & arr)

应该做你想做的,但是......

,但...

听起来你正试图重新发明轮子。不要这样做。除非这是一项任务或个人教育,否则就要坚持下去。

相反,请使用其中一个内置容器。

由于DIM1DIM2是常量,因此您可以使用

std::array<std::array<double, DIM2>,DIM1> myArray;

void funcCall(std::array<std::array<double, DIM2>,DIM1> arr)

但是你想要一个动态解决方案的可能性非常大。在这种情况下,请尝试

std::vector<std::vector<double>> myArray(DIM1, std::vector<double>(DIM2));

void funcCall(std::vector<std::vector<double>> arr)

,但...

说实话,这是一个糟透了的赌注。数组或向量向量在存储器中不连续,因此计算机必须在存储器中跳转,浪费时间在不必要的高速缓存未命中上,并且加载和可能重新加载高速缓存所花费的时间通常比所涉及的计算花费更长的时间。世界上所有的133t数学都无法帮助你,因为你已经被IO控制了,IO就是sssssssssslllloooowwwwwwww。

你真正想要的是一个很好的1维数组,它是手动编入索引的。带行*列数+列。当然,手动索引看起来像额外的工作,但停下来思考:编译器在后台做了多少数学运算才能让你的数组工作,嗯?可能差不多。你只是没有看到它。

现在让我们坚持使用std :: vector,但这同样适用于std :: array甚至是一个好的ol&#39;静态数组或智能指针内的动态。

std::vector<double> myArray(DIM1*DIM2);

使用它相对简单:

myArray[row*DIM2 + column];

功能是:

void funcCall(std::vector<double> arr)

但这很容易包含在课堂上并进一步简化:

class matrix
{
private: 
    std::vector<double> myArray;
    size_t nrRows;
    size_t nrColumns;

public:
    matrix(size_t rows, size_t columns): 
        myArray(rows*columns), nrRows(rows), nrColumns(columns)
    {

    }

    double& operator()(size_t row, size_t column)
    {
        return myArray[row* nrColumns + column];
    }
    double operator()(size_t row, size_t column) const
    {
        return myArray[row* nrColumns + column];
    }
};

结构:

matrix mat(DIM1, DIM2);

和用法:

double d = mat(1,2);

mat(2,1) = 3.14;
相关问题