本文介绍了如何从析构函数调用const成员函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

销毁const对象时,是否有可能从析构函数调用const成员函数?

Is there any possible way to invoke const member function from destructor, when const object is destroyed?

考虑:

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

    void show () {
        cout << "void show ()" << endl;
    }
    void show () const {
        cout << "void show () const" << endl;
    }
};

和用法:

My_type mt;
const My_type cmt;
mt.show ();
cmt.show ();

输出:

void show ()
void show () const
void show ()
void show ()

有人可以解释一下为什么 cmt 被破坏时为什么没有调用const版本的表演吗?

Can someone explain me why const version of show has not been invoked when cmt is destroyed?

推荐答案

const 实例上调用非const重载的原因是因为在销毁期间不会考虑当前实例上的cv限定词。 [class.dtor] / p2:

The reason the non-const overload is being called when on a const instance is because cv-qualifiers on the current instance aren't considered during destruction. [class.dtor]/p2:

您可以简单地将 * this 绑定到对 const 的引用来获得所需的行为:

You can use a simply bind *this to a reference to const to get the behavior you need:

~My_type() {
    My_type const& ref(*this);
    ref.show();
}

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

Or maybe you can use a wrapper that stores a reference and calls show() in its own destructor:

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);
};

这篇关于如何从析构函数调用const成员函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-25 04:20