54 lines · c
1//===----------------------------------------------------------------------===//2//3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.4// See https://llvm.org/LICENSE.txt for license information.5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception6//7//===----------------------------------------------------------------------===//8 9#ifndef _LIBCPP___UTILITY_NO_DESTROY_H10#define _LIBCPP___UTILITY_NO_DESTROY_H11 12#include <__config>13#include <__new/placement_new_delete.h>14#include <__utility/forward.h>15 16#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)17# pragma GCC system_header18#endif19 20_LIBCPP_BEGIN_NAMESPACE_STD21 22struct __uninitialized_tag {};23 24// This class stores an object of type _Tp but never destroys it.25//26// This is akin to using __attribute__((no_destroy)), except that it is possible27// to control the lifetime of the object with more flexibility by deciding e.g.28// whether to initialize the object at construction or to defer to a later29// initialization using __emplace.30template <class _Tp>31struct __no_destroy {32 _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR explicit __no_destroy(__uninitialized_tag) : __obj_() {}33 34 template <class... _Args>35 _LIBCPP_HIDE_FROM_ABI explicit __no_destroy(_Args&&... __args) {36 ::new ((void*)__obj_) _Tp(std::forward<_Args>(__args)...);37 }38 39 template <class... _Args>40 _LIBCPP_HIDE_FROM_ABI _Tp& __emplace(_Args&&... __args) {41 return *(::new ((void*)__obj_) _Tp(std::forward<_Args>(__args)...));42 }43 44 _LIBCPP_HIDE_FROM_ABI _Tp& __get() { return *reinterpret_cast<_Tp*>(__obj_); }45 _LIBCPP_HIDE_FROM_ABI _Tp const& __get() const { return *reinterpret_cast<const _Tp*>(__obj_); }46 47private:48 _ALIGNAS_TYPE(_Tp) char __obj_[sizeof(_Tp)];49};50 51_LIBCPP_END_NAMESPACE_STD52 53#endif // _LIBCPP___UTILITY_NO_DESTROY_H54