为什么 inplace Tensor 方法在 Torch C++ API 中是 const?

Why inplace Tensor methods are const in Torch C++ API?

我看到许多像 mul_div_ 这样的就地张量操作在 PyTorch C++ 前端是常量:

Tensor &mul_(Scalar other) const

似乎很奇怪,因为inplace操作应该修改张量数据,对吧?有谁知道使它们成为 const 背后的基本原理是什么?

我在 github 上找到了一些 discussions,但标题似乎与下面写的内容相矛盾:

'const Tensor' doesn't provide const safety ... Therefore, these methods should be non-const

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

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