• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2 * Copyright (c) 2024 Huawei Device Co., Ltd.
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 SMART_FD_H
17 #define SMART_FD_H
18 
19 #include <cstdint>
20 #include <unistd.h>
21 namespace OHOS {
22 namespace HiviewDFX {
23 class SmartFd {
24 public:
SmartFd(int32_t fd)25     SmartFd(int32_t fd) : fd_(fd) {}
26 
~SmartFd()27     ~SmartFd()
28     {
29         if (fd_ >= 0) {
30             close(fd_);
31         }
32     }
33 
34     SmartFd(const SmartFd&) = delete;
35 
36     SmartFd &operator=(const SmartFd&) = delete;
37 
SmartFd(SmartFd && rhs)38     SmartFd(SmartFd&& rhs) noexcept : fd_(rhs.fd_)
39     {
40         rhs.fd_ = -1;
41     }
42 
43     SmartFd& operator=(SmartFd&& rhs) noexcept
44     {
45         if (this != &rhs) {
46             if (fd_ >= 0) {
47                 close(fd_);
48             }
49             fd_ = rhs.fd_;
50             rhs.fd_ = -1;
51         }
52         return *this;
53     }
54 
int32_t()55     operator int32_t() const
56     {
57         return fd_;
58     }
59 private:
60     int32_t fd_;
61 };
62 }
63 }
64 #endif // SMART_FD_H
65