Where does torch::tensor create the object? stack or heap?

When I write:

torch::Tensor y = ... ;

where does the object y live? On the stack or on the heap?

If it is on the stack, how can I delete this allocated tensor y after I finished working with it?

Thank you!

Hi!

There’s some nice info here: Writing Python in cpp (a manifesto) · pytorch/pytorch Wiki · GitHub.

The short answer is that at::Tensor is a pointer type (like a shared pointer), with the pointer on the stack, and data on the heap. The pointer is freed when it goes out of scope. If you have multiple references to a tensor in c++, the data will be freed when the reference count drops to 0.

1 Like

Thank you very much! It answers all my doubts.