c++ - 为什么在Torch C++ API中就地Tensor方法是const?

标签 c++ libtorch

我看到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/

相关文章:

python - 与 PyTorch 的 torch.no_grad 等效的 LibTorch 是什么?

c++ - 在 Torch C++ API 中,如何快速写入张量的内部数据?

python - pytorch torch.jit.trace 返回函数而不是 torch.jit.ScriptModule

pytorch - 运行 TRTorch 示例时为 "error while loading shared libraries: libnvinfer.so.7: cannot open shared object file: No such file or directory"

c++ - "error: stray '\XXX ' in C++ program": Why does this happen?

c++ - 如何在 ADL 期间使功能模板成为最低优先级?

c++ - 为什么 Visual Studio 2013 对此类成员 decltype 有问题?

c++ - 如何确定 boost::variant 变量是否为空?

android - Qt 不检测 Android NDK

cmake - 链接静态库 pytorch 在构建过程中找不到其内部函数