C++ Atomic::operator T() function



The C++ std::atomic::operator T() function is a conversion operator that allows an std::atomic <T> object to be implicitly converted to its underlying type T. This function automatically retrieves the value of the std::atomic object, ensuring the operation is safe in concurrent environment.

Syntax

Following is the syntax for std::atomic::operator T() function.

operator T() const volatile noexcept;operator T() const noexcept;

Parameters

This function does not accept any parameter.

Return Value

It returns the current value of the atomic variable.

Exceptions

This member function never throws exceptions.

Example

In the following example, we are going to consider the basic usage of operator T() function.

#include <iostream>
#include <atomic>
int main()
{
    std::atomic<int> x(10);
    int value = x;
    std::cout << "Value: " << value << std::endl;
    return 0;
}

Output

Output of the above code is as follows −

Value: 10

Example

Consider the following example, where the main thread retrieves the final value of counter using the T() conversion operator.

#include <iostream>
#include <atomic>
#include <thread>
std::atomic<int> a(0);
void increment()
{
    for (int i = 0; i < 100; ++i) {
        ++a;
    }
}
int main()
{
    std::thread x(increment);
    std::thread y(increment);
    x.join();
    y.join();
    int finalCount = a;
    std::cout << "Final count: " << finalCount << std::endl;
    return 0;
}

Output

Following is the output of the above code −

Final count: 200
atomic.htm
Advertisements