xref: /aosp_15_r20/external/tensorflow/tensorflow/core/framework/tensor_reference.h (revision b6fb3261f9314811a0f4371741dbb8839866f948)
1 /* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
2 
3 Licensed under the Apache License, Version 2.0 (the "License");
4 you may not use this file except in compliance with the License.
5 You may obtain a copy of the License at
6 
7     http://www.apache.org/licenses/LICENSE-2.0
8 
9 Unless required by applicable law or agreed to in writing, software
10 distributed under the License is distributed on an "AS IS" BASIS,
11 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 See the License for the specific language governing permissions and
13 limitations under the License.
14 ==============================================================================*/
15 
16 #ifndef TENSORFLOW_FRAMEWORK_TENSOR_REFERENCE_H_
17 #define TENSORFLOW_FRAMEWORK_TENSOR_REFERENCE_H_
18 
19 #include "tensorflow/core/framework/tensor.h"
20 #include "tensorflow/core/lib/gtl/inlined_vector.h"
21 
22 namespace tensorflow {
23 
24 // An opaque class that holds a reference to an underlying TensorBuffer.
25 // Unlike Tensor, it does not have any shape or type information, so
26 // it is cheaper to construct/move, but the only thing you can really do
27 // with it is Unref it, which releases one of the references to the underlying
28 // TensorBuffer.
29 // IMPORTANT: If you do not call Unref(), you will likely leak tensor memory.
30 class TensorReference {
31  public:
32   // Take the reference of the root buffer so the size will be more accurate
TensorReference(const Tensor & tensor)33   explicit TensorReference(const Tensor& tensor)
34       : buf_(tensor.buf_ ? tensor.buf_->root_buffer() : nullptr) {
35     if (buf_) buf_->Ref();
36   }
37 
~TensorReference()38   ~TensorReference() {}
39 
Unref()40   void Unref() const {
41     if (buf_) buf_->Unref();
42   }
43 
FillDescription(AllocationDescription * description)44   void FillDescription(AllocationDescription* description) const {
45     if (buf_) buf_->FillAllocationDescription(description);
46   }
47 
48  private:
49   TensorBuffer* buf_;
50 };
51 
52 }  // namespace tensorflow
53 
54 #endif  // TENSORFLOW_FRAMEWORK_TENSOR_REFERENCE_H_
55