I have a class Stuff, with two functions foo (const and non-const):
class Stuff
{
public:
~Stuff() { foo(); }
void foo() const { cout << "const foo" << endl; }
void foo() { cout << "non-const foo" << endl; }
};
Here's what I am trying to do:
If the stuff was const, call const foo in the destructor of Stuff.
if the stuff wasn't const, call non-const foo in the destructor of Stuff.
I was hoping that just defining the destructor as shown above would work, but it turns out that the constness is stripped away right before executing the destructor (it is enforced right after the constructor completes, so I cannot set any flag there either). To make it clearer, here's an example:
{ Stuff stuff; }
{ const Stuff cstuff; }
This code prints "non-const foo" twice. I want it to print "non-const foo", followed by "const foo". Is that possible with C++?
EDIT: A few people are asking for more context. In the real code, stuff is basically a handle to some data. If stuff is accessed in a non-const manner, I assume that the data has been modified, so I need to communicate that to other processes (MPI) using the foo function (after I am done modifying it -> in the destructor, when I release the handle). If it was accessed in a const-manner, I know I don't need to transfer anything, so I am calling non-const foo, that does nothing.
[...]
const
andvolatile
semantics (7.1.6.1) are not applied on an object under destruction. They stop being in effect when the destructor for the most derived object (1.8) starts.
12.4/2 [class.dtor] in N4141.
So no, this is not possible.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With