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 NO_DESTRUCTOR_H
17 #define NO_DESTRUCTOR_H
18 
19 #include <new>
20 #include <utility>
21 
22 namespace OHOS {
23 namespace Bluetooth {
24 // Only used in Singleton pattern, for example: static BluetoothNoDestructor<SingletonDemo> instance;
25 template <typename T>
26 class BluetoothNoDestructor {
27 public:
28     template <typename... Args>
BluetoothNoDestructor(Args &&...args)29     explicit BluetoothNoDestructor(Args&&... args)
30     {
31         new (buff_) T(std::forward<Args>(args)...);
32     }
33 
BluetoothNoDestructor(const T & x)34     explicit BluetoothNoDestructor(const T& x) { new (buff_) T(x); }
BluetoothNoDestructor(T && x)35     explicit BluetoothNoDestructor(T&& x) { new (buff_) T(std::move(x)); }
36 
37     ~BluetoothNoDestructor() = default;
38 
39     BluetoothNoDestructor(const BluetoothNoDestructor&) = delete;
40     BluetoothNoDestructor& operator=(const BluetoothNoDestructor&) = delete;
41 
42     const T& operator*() const { return *get(); }
43     T& operator*() { return *get(); }
44 
get()45     const T* get() const { return reinterpret_cast<const T*>(buff_); }
get()46     T* get() { return reinterpret_cast<T*>(buff_); }
47 
48 private:
49     alignas(T) char buff_[sizeof(T)];
50 };
51 }  // namespace Bluetooth
52 }  // namespace OHOS
53 #endif  // NO_DESTRUCTOR_H
54