1 /*
2  * Copyright (C) 2015 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #ifndef UNIQUE_FD_H
18 #define UNIQUE_FD_H
19 
20 #include <stdio.h>
21 
22 #include <memory>
23 
24 class unique_fd {
25   public:
unique_fd(int fd)26     unique_fd(int fd) : fd_(fd) { }
27 
unique_fd(unique_fd && uf)28     unique_fd(unique_fd&& uf) {
29         fd_ = uf.fd_;
30         uf.fd_ = -1;
31     }
32 
~unique_fd()33     ~unique_fd() {
34         if (fd_ != -1) {
35             close(fd_);
36         }
37     }
38 
get()39     int get() {
40         return fd_;
41     }
42 
43     // Movable.
44     unique_fd& operator=(unique_fd&& uf) {
45         fd_ = uf.fd_;
46         uf.fd_ = -1;
47         return *this;
48     }
49 
50     explicit operator bool() const {
51         return fd_ != -1;
52     }
53 
54   private:
55     int fd_;
56 
57     // Non-copyable.
58     unique_fd(const unique_fd&) = delete;
59     unique_fd& operator=(const unique_fd&) = delete;
60 };
61 
62 #endif  // UNIQUE_FD_H
63