gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 22:37:23 25 4
gpt4 key购买 nike

我有一个类 Stuff,有两个函数 foo(const 和 non-const):

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

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

这是我想要做的:

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

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

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

{ Stuff stuff; }
{ const Stuff cstuff; }

这段代码打印了两次“non-const foo”。我希望它打印“non-const foo”,然后打印“const foo”。用 C++ 可以吗?

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

N4141 中的 12.4/2 [class.dtor]。

所以不,这是不可能的。

关于c++ - 找出对象在其析构函数中的常量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53840945/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com