class CCounter
{
public:
CCounter(int nVal = 0) : m_nVal(nVal) {}
int operator++(int) { int nVal = m_nVal; ++m_nVal; return nVal; }
int operator++() { m_nVal++; return m_nVal; }
int m_nVal;
};
There are non-member function template equivalents for all member functions of std::atomic. Those non-member functions may be additionally overloaded for types that are not specializations of std::atomic, but are able to guarantee atomicity. The only such type in the standard library is std::shared_ptr<T>.For an atomic type of T only assignment is available, which is achieve via in-place constructor (hence the need for the class to be trivially copy constructable). The std::atomic assignment operator makes sure this is an atomic operation, which it can do because the object (and hence all the members) are trivially copy constructable. So, in that respect, you need to nothing special for assignment; by default the std:atomic class with ensure that is always atomic.
#include <atomic>
class foo
{
public:
foo(int x = 0) noexcept
: x_(x)
{
}
foo operator + (foo rhs) const
{
return rhs.x_ + rhs.x_;
}
private:
int x_;
};
template<typename T>
foo operator +(std::atomic<T> const & lhs, T const & rhs)
{
return lhs.load() + rhs;
}
int main()
{
auto && a = std::atomic<foo>(foo(1));
auto && b = a + foo(2);
}
#include <atomic>
class foo
{
public:
foo(int x = 0) noexcept
: x_(x)
{
}
foo & operator += (foo rhs)
{
x_ += rhs.x_;
return *this;
}
private:
int x_;
};
template<typename T>
std::atomic<T> operator +=(std::atomic<T> & lhs, T const & rhs)
{
return lhs.load() += rhs;
}
int main()
{
auto && a = std::atomic<foo>(foo(1));
a += foo(2);
}
#include <atomic>
class foo
{
public:
foo(int x = 0) noexcept
: x_(x)
{
}
foo operator ++()
{
return ++x_;
}
private:
int x_;
};
template<typename T>
std::atomic<T> & operator ++(std::atomic<T> & x)
{
x.store(++x.load());
return x;
}
int main()
{
auto && a = std::atomic<foo>(foo(1));
++a;
}
ASKER
ASKER
C++ is an intermediate-level general-purpose programming language, not to be confused with C or C#. It was developed as a set of extensions to the C programming language to improve type-safety and add support for automatic resource management, object-orientation, generic programming, and exception handling, among other features.
TRUSTED BY
Thank you, Sara - that's very kind of you.