如何从析构函数中调用const成员函数

Art*_*zuk 27 c++ destructor c++11

当const对象被销毁时,有没有办法从析构函数中调用const成员函数?

考虑:

struct My_type { 
    ~My_type () { 
        show ();
    }

    void show () { 
        cout << "void show ()" << endl;
    }
    void show () const { 
        cout << "void show () const" << endl;
    }
};
Run Code Online (Sandbox Code Playgroud)

用法:

My_type mt;
const My_type cmt;
mt.show ();
cmt.show ();
Run Code Online (Sandbox Code Playgroud)

输出:

void show ()
void show () const
void show ()
void show ()
Run Code Online (Sandbox Code Playgroud)

有人可以解释一下为什么cmt被销毁时没有调用const版本的show ?

0x4*_*2D2 18

const实例上调用非const重载的原因是因为在销毁期间不考虑当前实例上的cv-qualifiers.[class.dtor]/P2:

析构函数用于销毁其类类型的对象.不得采用析构函数的地址.可以为const,volatile或const volatile对象调用析构函数.constvolatile 语义(7.1.6.1)不适用于被破坏的对象.当最派生对象(1.8)的析构函数启动时,它们将停止生效.

您可以使用简单绑定*this到引用const来获取所需的行为:

~My_type() { 
    My_type const& ref(*this);
    ref.show();
}
Run Code Online (Sandbox Code Playgroud)

或者也许您可以使用一个包装器来存储引用并show()在其自己的析构函数中调用:

template<class T>
struct MyTypeWrapper : std::remove_cv_t<T> {
    using Base = std::remove_cv_t<T>;
    using Base::Base;

    T&       get()       { return ref; }
    T const& get() const { return ref; }

    ~MyTypeWrapper() { ref.show(); }
private:
    T& ref = static_cast<T&>(*this);
};
Run Code Online (Sandbox Code Playgroud)