views:

230

answers:

1

In the following example, I get:

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

If I remove the operator->, this error goes away. Could someone explain why this is happening?

// 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  A: 

You're overriding the -> operator, so when you do:

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

You're effectively calling

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

I believe you can work around this by doing this, though:

~SmartPointer() { (*this).!SmartPointer(); }
Reed Copsey
That makes sense Reed, thank you; can't believe I didn't realize that. Unfortunately I have operator* overloaded as well. Just doing ~SmartPointer() { !SmartPointer(); }doesn't work either.
Ryan
Got it: ~SmartPointer() { SmartPointer::!SmartPointer(); }Thanks again. Ryan
Ryan