我看到PyTorch C++前端中有许多就位的Tensor操作(例如mul_
和div_
)都是const:
Tensor &mul_(Scalar other) 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的常量指针)之间的区别。
在函数名称中没有最后一个下划线的情况下,很容易识别出割炬中的常量(非常量)函数。
关于c++ - 为什么在Torch C++ API中就地Tensor方法是const?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63434710/