Код: Выделить всё
#include
#include
template
class ThreadSafeVar
{
T value;
std::mutex mutex{};
public:
template
ThreadSafeVar(Args&&... args) : value{ std::forward(args)... } {}
ThreadSafeVar(ThreadSafeVar&) = delete;
ThreadSafeVar(ThreadSafeVar&&) = delete;
ThreadSafeVar& operator=(ThreadSafeVar&) = delete;
ThreadSafeVar& operator=(ThreadSafeVar&&) = delete;
class Lock
{
friend class ThreadSafeVar;
T& ref;
std::unique_lock lock;
Lock(ThreadSafeVar* tsvar) : ref{ tsvar->value }, lock{ tsvar->mutex } {}
public:
T & get() const { return ref; }
};
Lock lock() { return Lock{ this }; }
};
template
using ThreadSafePtr = std::shared_ptr;
template
constexpr auto ThreadSafePtr_make = std::make_shared;
template
constexpr ThreadSafePtr(*ThreadSafePtr_make2)(Args&&...) = &std::make_shared;
int main()
{
ThreadSafePtr a = std::make_shared(2);
a->lock().get()++;
ThreadSafePtr b = ThreadSafePtr_make();
ThreadSafePtr c = ThreadSafePtr_make(2); // fail, too many arguments
ThreadSafePtr d = ThreadSafePtr_make2(2); // fail, too many arguments
return 0;
}
Подробнее здесь: https://stackoverflow.com/questions/795 ... ake-shared
Мобильная версия