在c++中将原始指针更改为智能指针

Changing raw pointers to smart in C++

本文关键字:指针 智能 原始 c++      更新时间:2023-10-16

有一个简单的函数创建一个存储在数组中的零填充矩阵。

void zeroMatrix(const int rows, const int columns, void* M)
{
   for(int i = 0; i < rows; i++)
       for(int j = 0; j < columns; j++)
          *(((double *)M) + (rows * i) + j) = 0;
}

如何更改代码以使用std::unique_ptr<double>作为M?

由于没有所有权转移到zeroMatrix函数,因此您需要的是引用:

(假设M是向量)

void zeroMatrix(const int rows, const int columns, std::vector<double> &M)
{
   for(int i = 0; i < rows; i++)
       for(int j = 0; j < columns; j++)
          M[(rows * i) + j] = 0;
}