C ++ / CLI终结器和操作符

时间:2009-05-06 17:02:00

标签: .net c++-cli managed-c++

在以下示例中,我得到:

error C2300: 'UnmanagedClass' : class does not have a finalizer called '!SmartPointer'

如果我删除了operator-&gt ;,则此错误消失。有人可以解释为什么会这样吗?

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

1 个答案:

答案 0 :(得分:5)

你要覆盖 - >运算符,所以当你这样做时:

~SmartPointer() { this->!SmartPointer(); }

您正在有效地致电

~SmartPointer() { m_ptr->!SmartPointer(); }

我相信你可以通过这样做来解决这个问题:

~SmartPointer() { (*this).!SmartPointer(); }