如何从析构函数调用const成员函数 [英] How can I call const member function from destructor

查看:156
本文介绍了如何从析构函数调用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:


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

A destructor is used to destroy objects of its class type. The address of a destructor shall not be taken. A destructor can be invoked for a const, volatile or const volatile object. 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.

您可以简单地将 * 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成员函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆