当const对象被销毁时,有没有可能从析构函数调用const成员函数的方法?
考虑:
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版本的show吗?
在const
实例上调用非const重载的原因是因为在销毁过程中不考虑当前实例上的cv限定词。[class.dtor] / p2:
析构函数用于销毁其类类型的对象。不得使用析构函数的地址。可以为const,volatile或const volatile对象调用析构函数。
const
和volatile
语义(7.1.6.1)不适用于正在销毁的对象。当最派生对象(1.8)的析构函数启动时,它们停止生效。
您可以使用简单绑定*this
到引用const
来获得所需的行为:
~My_type() {
My_type const& ref(*this);
ref.show();
}
或者,也许您可以使用一个存储引用并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);
};
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句