在c++中将原始指针更改为智能指针
Changing raw pointers to smart in C++
有一个简单的函数创建一个存储在数组中的零填充矩阵。
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;
}
相关文章:
- 1d 智能指针不适用于语法 (*)++
- 优先顺序:智能指针和类析构函数
- 对于C++中使用智能指针的指针算术限制,有没有一种变通方法
- 智能指针作为无序映射键,并通过引用进行比较
- 智能指针概念所有权和寿命
- 正在理解智能指针,但出现错误:未分配正在释放的指针
- 尝试使用智能指针时引发异常
- 我可以制作指向智能指针的智能指针吗?
- 通过智能指针和转换对基本模板参数进行模板推导
- OpenCV 我应该使用智能指针来防止内存泄漏吗?
- 从堆栈分配的原始指针构造智能指针
- 初始化指向类实例的智能指针并访问其方法
- 如何使用 std::make_shared 创建基类类型的智能指针?
- 给定一个指向堆分配内存的指针,智能指针实现如何为其找到合适的释放函数?
- 编译器不会使用 -std=c++11 编译智能指针
- 具有智能指针的多态性
- C++:矢量分配器行为、内存分配和智能指针
- 通过简单的包装指针C++智能指针性能和差异
- 矢量中的自动指针(智能)
- Std::vector的对象/指针/智能指针传递对象(总线错误:10)