在以下示例中,我得到:
error C2300: 'UnmanagedClass' : class does not have a finalizer called '!SmartPointer'
如果删除运算符->,此错误将消失。有人可以解释为什么会这样吗?
// Unmanaged class.
class UnmanagedClass { };
public ref class SmartPointer {
public:
SmartPointer(UnmanagedClass* u) : m_ptr(u) { }
~SmartPointer() { this->!SmartPointer(); }
!SmartPointer() { delete m_ptr; }
// This line triggers C2300.
UnmanagedClass* operator->() { return m_ptr; }
};
int main() {
SmartPointer^ s = gcnew SmartPointer(new UnmanagedClass);
}
最佳答案
您将覆盖->运算符,因此在执行以下操作时:
~SmartPointer() { this->!SmartPointer(); }
您实际上是在打电话
~SmartPointer() { m_ptr->!SmartPointer(); }
我相信您可以通过以下方法解决此问题:
~SmartPointer() { (*this).!SmartPointer(); }