/* This file is part of Telegram Desktop, the official desktop version of Telegram messaging app, see https://telegram.org Telegram Desktop is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. It 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. In addition, as a special exception, the copyright holders give permission to link the code of portions of this program with the OpenSSL library. Full license: https://github.com/telegramdesktop/tdesktop/blob/master/LICENSE Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org */ #pragma once namespace base { class enable_weak_from_this; template ::value>> class weak_unique_ptr; class enable_weak_from_this { public: enable_weak_from_this() = default; enable_weak_from_this(const enable_weak_from_this &other) noexcept { } enable_weak_from_this(enable_weak_from_this &&other) noexcept { } enable_weak_from_this &operator=(const enable_weak_from_this &other) noexcept { return *this; } enable_weak_from_this &operator=(enable_weak_from_this &&other) noexcept { return *this; } private: template friend class weak_unique_ptr; std::shared_ptr getGuarded() { if (!_guarded) { _guarded = std::make_shared(this); } return _guarded; } std::shared_ptr _guarded; }; template class weak_unique_ptr { public: weak_unique_ptr() = default; weak_unique_ptr(T *value) : _guarded(value ? value->getGuarded() : std::shared_ptr()) { } weak_unique_ptr(const std::unique_ptr &value) : _guarded(value ? value->getGuarded() : std::shared_ptr()) { } T *get() const noexcept { if (auto shared = _guarded.lock()) { return static_cast(*shared); } return nullptr; } explicit operator bool() const noexcept { return !!_guarded.lock(); } T &operator*() const noexcept { return *get(); } T *operator->() const noexcept { return get(); } private: std::weak_ptr _guarded; }; } // namespace base