找出对象在其析构函数中的常量

Figuring out the constness of an object within its destructor

我有一个 class 东西,有两个函数 foo(const 和非常量):

class Stuff
{
public:
    ~Stuff() { foo(); }

    void foo() const { cout << "const foo" << endl; }
    void foo()       { cout << "non-const foo" << endl; }
};

这是我正在尝试做的事情:

  1. 如果stuff是const,在Stuff的析构函数中调用const foo。

  2. 如果东西不是 const,在 Stuff 的析构函数中调用非 const foo。

我希望只定义如上所示的析构函数就可以工作,但事实证明,constness 在执行析构函数之前就被剥离了(它在构造函数完成后立即强制执行,所以我无法设置任何标志也有)。为了更清楚,这里有一个例子:

{ Stuff stuff; }
{ const Stuff cstuff; }

此代码打印 "non-const foo" 两次。我希望它打印 "non-const foo",然后是 "const foo"。用 C++ 可以吗?

编辑:一些人要求提供更多背景信息。在实际代码中,stuff 基本上是一些数据的句柄。如果以非常量方式访问内容,我假设数据已被修改,因此我需要使用 foo 函数将其传达给其他进程(MPI)(在我完成修改后 -> 在析构函数中,当我松开手柄)。如果以常量方式访问它,我知道我不需要传输任何东西,所以我调用非常量 foo,它什么都不做。

[...] const and volatile 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] 在 N4141。

所以不,这是不可能的。