I have a std:atomic_bool which I have defined as this in my code:
class A
{
public:
A();
A(const A&);
~A();
std::atomic_bool isTrue;
}
A:A()
{
isTrue= false;
}
A::A(const A&) : isTrue(false)
{}
Then I do the following:
class B
{
A aObj;
public:
bool getBool()
{
return GetNumberOfUsers() > 1 ? aObj.isTrue : true;
}
I get the following error on the getBool()
function.
Error C2280 'std::atomic::atomic(const std::atomic &)': attempting to reference a deleted function
I understand that this happens because the copy constructor of atomics are deleted. But I have followed this answer and have defined the copy constructor. I am at a lost why the error is still coming up. I also tried:
class A
{
...
A(const A&) = delete;
But still got the error.
Edit: After some troubleshooting I came across a strange behavior. I found out that if I change my ternary if conditional in B::getBool() as the following, I will not get the error.
bool getBool()
{
// return GetNumberOfUsers() > 1 ? aObj.isTrue : true;
if (GetNumberOfUsers() > 1)
return aObj.isTrue ;
else
return true;
}
Now this is even more confusing.
EDIT 2:
After a little more troubleshooting I found the issue is probably the return type.
in a ternary if conditional exp1 ? exp2 : exp3
, the return type is the type of exp2 (as explained here).
So in this case, the return type of B::getBool() becomes atomic_bool, not atomic.
When I added a static_cast
the code to the following I do not get the error anymore.
bool getBool()
{
return GetNumberOfUsers() > 1 ? static_cast<bool>(aObj.isTrue) : true;
}
However I still don't know why this would throw the copy constructor error. Thank you.