首页 > 解决方案 > 为什么在 Torch C++ API 中就地张量方法是 const 的?

问题描述

我在 PyTorch C++ 前端看到很多就地张量操作,例如mul_和const:div_

Tensor &mul_(Scalar other) const

这似乎很奇怪,因为就地操作应该修改张量数据,对吧?有谁知道使它们成为常量的原因是什么?

我在 github 上找到了一些讨论,但看起来标题与下面写的内容相矛盾:

'const Tensor' 不提供 const 安全性......因此,这些方法应该是非常量的

标签: c++libtorch

解决方案


正如评论和这个线程所强调的那样,这const是不诚实的,因为它适用于指向底层的指针TensorImpl,而不是数据本身。这只是为了编译优化,这里没有真正的语义。const int*这类似于(pointer to const int) 和int* const(const pointer to int)之间的区别。

torch 中的 const (resp. non-const)函数很容易识别,因为函数名称中没有最后一个下划线(resp。存在)。


推荐阅读