// Copyright 2014 The Android Open Source Project // // This software is licensed under the terms of the GNU General Public // License version 2, as published by the Free Software Foundation, and // may be copied, distributed, and modified under those terms. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. #pragma once #include "anbox/common/type_traits.h" #include #include #include #include namespace anbox { namespace common { struct FreeDelete { template void operator()(T ptr) const { free(ptr); } }; template struct FuncDelete { explicit FuncDelete(Func f = {}) : mF(f) {} FuncDelete(const FuncDelete& other) = default; FuncDelete(FuncDelete&& other) = default; FuncDelete& operator=(const FuncDelete& other) = default; FuncDelete& operator=(FuncDelete&& other) = default; // To be able to copy/move from all compatible template instantiations. template friend struct FuncDelete; // Template constructors and move assignment from compatible instantiations. template FuncDelete(const FuncDelete& other) : mF(other.mF) {} template FuncDelete(FuncDelete&& other) : mF(std::move(other.mF)) {} template FuncDelete& operator=(const FuncDelete& other) { mF = other.mF; return *this; } template FuncDelete& operator=(FuncDelete&& other) { mF = std::move(other.mF); return *this; } // This is the actual deleter call. template void operator()(T t) const { mF(t); } private: Func mF; }; template > using ScopedPtr = std::unique_ptr; template using ScopedCPtr = std::unique_ptr; template using ScopedCustomPtr = std::unique_ptr>; // A factory function that creates a scoped pointer with |deleter| // function used as a deleter - it is called at the scope exit. // Note: enable_if<> limits the scope of allowed arguments to pointers and // std::nullptr_t (to allow makeCustomScopedPtr(nullptr, ...) calls). template ::value || std::is_pointer::value>> ScopedCustomPtr< typename std::decay::type>::type, typename std::decay::type> makeCustomScopedPtr(T data, Func deleter) { return ScopedCustomPtr< typename std::decay::type>::type, typename std::decay::type>( data, FuncDelete::type>(deleter)); } } // namespace common } // namespace anbox